public class VolatileExample {
private volatile boolean flag = false;
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean isFlag() {
return flag;
}
public static void main(String[] args) throws InterruptedException {
VolatileExample example = new VolatileExample();
Thread t1 = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
example.setFlag(true);
System.out.println("Flag has been set to true.");
});
Thread t2 = new Thread(() -> {
while (!example.isFlag()) {
// Busy-waiting until flag is set to true
}
System.out.println("Flag detected as true by t2.");
});
t2.start();
t1.start();
t1.join();
t2.join();
}
}
volatile 关键字的作用:
volatile 关键字用于修饰变量,确保该变量的值在多个线程之间保持一致。它防止了编译器和处理器对变量的读写操作进行重排序,并确保每次读取的是最新的值。代码逻辑:
volatile 布尔类型的变量 flag。t1 会在启动后等待 2 秒,然后将 flag 设置为 true 并打印一条消息。t2 会不停地检查 flag 的值,直到它变为 true。一旦 flag 变为 true,它会打印一条消息并退出循环。为什么需要 volatile:
volatile,线程 t2 可能会一直读取到 flag 的旧值(即 false),即使 t1 已经将其设置为 true。使用 volatile 确保了 t2 总是读取到最新的值。上一篇:java连接oracle数据库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站