public class VolatileExample {
private static volatile boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("Thread 1 is waiting for flag to be true...");
while (!flag) {
// Busy-waiting until flag becomes true
}
System.out.println("Thread 1 noticed the change in flag!");
});
Thread t2 = new Thread(() -> {
try {
// Simulate some work being done
Thread.sleep(2000);
System.out.println("Thread 2 setting flag to true...");
flag = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
volatile
关键字用于修饰变量,确保该变量的修改对所有线程立即可见。在多线程环境中,使用 volatile
可以避免线程之间的可见性问题。flag
被声明为 volatile
,这保证了当一个线程修改了 flag
的值时,其他线程能够立即看到这个变化。t1
会忙等待(busy-wait)直到 flag
被设置为 true
,而线程 t2
模拟了一些工作后将 flag
设置为 true
。volatile
避免了由于指令重排序或缓存导致的可见性问题,但请注意,volatile
并不能替代锁机制来保证原子性操作。上一篇:java assert用法
下一篇:java中i++与++i
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站