挥发性布尔VS的AtomicBoolean [英] Volatile boolean vs AtomicBoolean

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

问题描述

这是什么的AtomicBoolean做挥发性布尔无法实现?

What does AtomicBoolean do that a volatile boolean cannot achieve?

推荐答案

他们只不过是完全不同的。考虑一个挥发性整数这个例子:

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

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

如果两个线程调用的函数同时, I 可能是5算账,因为编译code会有点类似这个(除非您不能同步于 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 }
}

如果一个变量是挥发性的,到它的每一个原子访问是同步的,但它并不总是明显究竟资格作为一个原子访问。随着原子* 的对象,这是保证每一个方法是原子。

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

因此​​,如果您使用的AtomicInteger getAndAdd(INT三角洲),可以肯定的是,结果将 10 。以同样的方式,如果两个线程都否定一个布尔变量同时,与的AtomicBoolean 你可以肯定它有原来的值之后,用挥发性布尔,你不能。

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.

的目的挥发性是不同的。考虑这个例子

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

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

如果你有一个线程中运行循环()和另一个线程调用停止(),你可能会遇到一个无限循环如果省略挥发性,因为第一个线程可能缓存停止的价值。在这里,挥发性作为提示编译器要多一点小心的优化。

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.

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

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