写了几行代码测试锁的问题,结果发现了一个调用Thread.sleep()的问题:
```public class Main {
public static int value = 0;
public static int value2 = 0;
public static AtomicInteger aValue = new AtomicInteger(0);
public static synchronized void increment2(){
value2++;
}
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
value++;
Main.increment2();
Main.aValue.getAndIncrement();
}
}).start();
}
Thread.sleep(100); //问题在这一行!!!!!****
System.out.println(Main.aValue);
}
}
问题是: 理论上,我创造1000个线程分别对变量加一,执行完循环后,如果不加Thread.sleep(),打印出的三个value全是0,但是只有加上sleep,才能打印出理想结果,我想不明白这是什么原理。