public class VolatileDemo {
// volatile 变量
private volatile static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
count++;
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
count++;
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(count);
}
}
以上是 volatile 不能保证并发安全的经典代码了,最终 count 结果不是 2000 。 count ++ 有三步,从主存读 count 到线程缓存,线程让 count + 1,线程写回 count 到主存
volatile 保证了 线程让 count + 1,线程写回 count 到主存 这两个操作是原子的,但没有保证三个操作是原子的,所以导致
thread1 读到 count
thread2 读到 count
thread2 让 count + 1
thread2 写回 count
thread1 让 count+1
thead1 写回 count
这种情况可能发生。而一旦发生的话,count 就少加了一次 1,所以最终结果不是 2000 。
这样理解对吗?谢谢