int value = 0;
volatile boolean done = false;
// Thread A:
value = 1; done = true;
// Thread B:
if (done) System.out.println(value);
很好,因为完成被定义为 volatile 。
关于相同的代码,除了将done定义为AtomicBoolean之外,它将实现相同的效果吗?换句话说,除了原子操作和可见操作以外,原子操作(RMW)是否还可以确保所有先前的写入都刷新到共享内存中?
int value = 0;
AtomicBoolean done = new AtomicBoolean(false);
// Thread A:
value = 1; done.set(true);
// Thread B:
if (done.get()) System.out.println(value);
最佳答案
From the Javadoc of java.util.concurrent
:
The memory effects for accesses and updates of atomics generally follow the rules for volatiles, as stated in The Java Language Specification (17.4 Memory Model):
- get has the memory effects of reading a volatile variable.
- set has the memory effects of writing (assigning) a volatile variable.
- ...
因此,在这种情况下,
volatile
和AtomicBoolean
之间没有区别。
关于java - volatile 和原子之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61793026/