读写是原子的
用于参考变量和大多数原始变量(除long和double以外的所有类型)。现在,我想知道为什么在下面的示例中,必须使用volatile关键字来防止无限循环-int变量的更改应该是原子的,因此每个人都可以立即看到,不是吗?
public class HelloWorld
{
// This doesn't work as expected
private static int x = 0;
//Following would work: private volatile static int x = 0;
public static void main(String []args) throws Exception
{
Thread t1 = new Thread(() -> {
try
{
Thread.sleep(1000);
x = 1; //Should be atomic, right?
} catch (InterruptedException e) {}
});
System.out.println("Begin");
t1.start();
//The evaluation of the condition should also be atomic, right?
while(x == 0)
{
}
t1.join();
System.out.println("End");
}
}
Oracle文档指出:对于参考变量和大多数原始变量(除了long和double以外的所有类型),读写是原子的。现在我想知道为什么volatile关键字是...
原子