代码如下:
开启10个线程,对inc方法加synchronized进行锁定,但是输出的是0-10的随机数。并不是10,这是为什么呢?
public class testVolatile {
public static int count = 0;
public static synchronized void inc() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
testVolatile.inc();
}
}).start();
}
synchronized (testVolatile.class) {
System.out.println("运行结果:Counter.count=" + testVolatile.count);
}
}
}