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

问题描述

使用 volatile 原语(例如 boolean integer long )而不是 AtomicBoolean AtomicInteger $ c> AtomicLong ,反之亦然?

解决方案


例如:

pre> if(volatileBoolean){
volatileBoolean =!volatileBoolean;
}

可能会在多线程环境中创建问题,因为变量可能在两个线。如果你需要测试和赋值为原子,你可以使用:

  atomicBoolean.compareAndSet(true,false); 


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.

For example:

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原语有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:25