挥发性布尔值与原子布尔值 [英] Volatile boolean vs AtomicBoolean

查看:49
本文介绍了挥发性布尔值与原子布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AtomicBoolean 做了哪些 volatile boolean 无法实现的事情?

What does AtomicBoolean do that a volatile boolean cannot achieve?

推荐答案

它们只是完全不同的.考虑这个 volatile 整数的例子:

They are just totally different. Consider this example of a volatile integer:

volatile int i = 0;
void incIBy5() {
    i += 5;
}

如果两个线程同时调用该函数,i 之后可能是 5,因为编译后的代码会有点类似于这个(除了你不能在 int 上同步):

If two threads call the function concurrently, i might be 5 afterwards, since the compiled code will be somewhat similar to this (except you cannot synchronize on int):

void incIBy5() {
    int temp;
    synchronized(i) { temp = i }
    synchronized(i) { i = temp + 5 }
}

如果一个变量是 volatile,则对它的每一次原子访问都是同步的,但实际上什么是原子访问并不总是很明显.使用 Atomic* 对象,可以保证每个方法都是原子的".

If a variable is volatile, every atomic access to it is synchronized, but it is not always obvious what actually qualifies as an atomic access. With an Atomic* object, it is guaranteed that every method is "atomic".

因此,如果您使用 AtomicIntegergetAndAdd(int delta),您可以确定结果将是 10.以同样的方式,如果两个线程同时否定一个 boolean 变量,使用 AtomicBoolean 你可以确定它之后具有原始值,使用 volatile boolean,你不能.

Thus, if you use an AtomicInteger and getAndAdd(int delta), you can be sure that the result will be 10. In the same way, if two threads both negate a boolean variable concurrently, with an AtomicBoolean you can be sure it has the original value afterwards, with a volatile boolean, you can't.

因此,每当您有多个线程修改一个字段时,您都需要使其原子化或使用显式同步.

So whenever you have more than one thread modifying a field, you need to make it atomic or use explicit synchronization.

volatile 的目的是不同的.考虑这个例子

The purpose of volatile is a different one. Consider this example

volatile boolean stop = false;
void loop() {
    while (!stop) { ... }
}
void stop() { stop = true; }

如果你有一个线程运行 loop() 和另一个线程调用 stop(),如果你省略 volatile,你可能会遇到无限循环code>,因为第一个线程可能会缓存 stop 的值.在这里,volatile 提示编译器在优化时要更加小心.

If you have a thread running loop() and another thread calling stop(), you might run into an infinite loop if you omit volatile, since the first thread might cache the value of stop. Here, the volatile serves as a hint to the compiler to be a bit more careful with optimizations.

这篇关于挥发性布尔值与原子布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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