Java 并发 - AtomicBoolean 类
java.util.concurrent.atomic.AtomicBoolean 类提供对可原子读写的底层布尔值的操作,并且还包含高级原子操作。 AtomicBoolean 支持对底层布尔变量进行原子操作。 它具有 get 和 set 方法,其工作方式类似于对易失性变量进行读取和写入。 也就是说,集合与同一变量上的任何后续获取具有先发生关系。 原子compareAndSet方法也具有这些内存一致性特性。
AtomicBoolean 方法
以下是 AtomicBoolean 类中可用的重要方法的列表。
| Sr.No. | 方法及描述 |
|---|---|
| 1 | public boolean compareAndSet(boolean expect, boolean update) 如果当前值 == 预期值,则自动将该值设置为给定的更新值。 |
| 2 | public boolean get() 返回当前值。 |
| 3 | public boolean getAndSet(boolean newValue) 自动设置为给定值并返回之前的值。 |
| 4 | public void lazySet(boolean newValue) 最终设置为给定值。 |
| 5 | public void set(boolean newValue) 无条件设置为给定值。 |
| 6 | public String toString() 返回当前值的字符串表示形式。 |
| 7 | public boolean weakCompareAndSet(boolean expect, boolean update) 如果当前值 == 预期值,则自动将该值设置为给定的更新值。 |
示例
以下 TestThread 程序显示了 AtomicBoolean 变量在基于线程的环境中的用法。
import java.util.concurrent.atomic.AtomicBoolean;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
new Thread("Thread 1") {
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()
+" Waiting for Thread 2 to set Atomic variable to true. Current value is "
+ atomicBoolean.get());
if(atomicBoolean.compareAndSet(true, false)) {
System.out.println("Done!");
break;
}
}
};
}.start();
new Thread("Thread 2") {
public void run() {
System.out.println(Thread.currentThread().getName() +
", Atomic Variable: " +atomicBoolean.get());
System.out.println(Thread.currentThread().getName() +
" is setting the variable to true ");
atomicBoolean.set(true);
System.out.println(Thread.currentThread().getName() +
", Atomic Variable: " +atomicBoolean.get());
};
}.start();
}
}
这将产生以下结果。
输出
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false Thread 2, Atomic Variable: false Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false Thread 2 is setting the variable to true Thread 2, Atomic Variable: true Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false Done!

