Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

volatile java

作者:遥岚月刹   发布日期:2025-05-26   浏览:61

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

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站