gpt4 book ai didi

java - volatile 和原子之间的区别

转载 作者:行者123 更新时间:2023-12-03 13:16:46 25 4
gpt4 key购买 nike

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.
  • ...


因此,在这种情况下, volatileAtomicBoolean之间没有区别。

关于java - volatile 和原子之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61793026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com