Java中Boolean的原子类型
时间: 2024-02-24 09:58:17 浏览: 126
Java 中提供了 `AtomicBoolean` 类型,它是 `java.util.concurrent.atomic` 包中的一个类,用于实现原子性的操作。`AtomicBoolean` 类用于在多线程环境中以原子方式更新 `boolean` 类型的值,确保多线程环境下的线程安全性。
`AtomicBoolean` 类提供了一系列原子性的方法,包括 `get()`、`set()`、`compareAndSet()`、`getAndSet()` 等,这些方法都是线程安全的,可以保证在多线程环境中正确地执行。
下面是一个使用 `AtomicBoolean` 类型的示例:
```java
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicBooleanExample {
private static AtomicBoolean flag = new AtomicBoolean(false);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
while (!flag.get()) {
System.out.println("Thread 1 is running.");
}
System.out.println("Thread 1 is done.");
});
Thread t2 = new Thread(() -> {
flag.set(true);
System.out.println("Thread 2 is done.");
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
```
在上面的示例中,我们使用 `AtomicBoolean` 类型的变量 `flag` 来控制线程的执行流程。线程 1 会一直循环执行,直到 `flag` 的值变为 `true`,而线程 2 则会在执行完后将 `flag` 的值设为 `true`,从而触发线程 1 的退出。
阅读全文
相关推荐



















