在原子变量上使用 volatile 原语有什么区别? [英] What is the difference between using a volatile primitive over atomic variables?

查看:31
本文介绍了在原子变量上使用 volatile 原语有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java:volatile boolean vs AtomicBoolean

什么时候适合使用 volatile 原语(例如 booleanintegerlong)而不是AtomicBooleanAtomicIntegerAtomicLong,反之亦然?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆