在原子变量上使用 volatile 原语有什么区别? [英] What is the difference between using a volatile primitive over atomic variables?
问题描述
可能的重复:
Java:volatile boolean vs AtomicBoolean
什么时候适合使用 volatile
原语(例如 boolean
、integer
或 long
)而不是AtomicBoolean
、AtomicInteger
或 AtomicLong
,反之亦然?
When is it appropriate to use a volatile
primitive (e.g. boolean
, integer
or long
) instead of AtomicBoolean
, AtomicInteger
or AtomicLong
, and vice-versa?
推荐答案
可见性语义完全一样,使用原子原语有用的情况是当你需要使用它们的原子方法时.
The visibility semantics are exactly the same, the situation where using the atomic primitives is useful is when you need to use their atomic methods.
例如:
if (volatileBoolean) {
volatileBoolean = !volatileBoolean;
}
可能会在多线程环境中产生问题,因为变量可能会在两行之间发生变化.如果你需要测试和赋值是原子的,你可以使用:
could create issues in a multi threaded environment as the variable could change between the two lines. If you need the test&assignment to be atomic, you can use:
atomicBoolean.compareAndSet(true, false);
这篇关于在原子变量上使用 volatile 原语有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!