如果读写是原子性的,为什么需要volatile?

问题描述 投票:0回答:1
此问题已经在这里有了答案:

Oracle documentation指出:

读写是原子的

用于参考变量和大多数原始变量(除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关键字是...
java multithreading volatile
1个回答
2
投票
读取和写入是

原子

© www.soinside.com 2019 - 2024. All rights reserved.