JAVA volatile 的一个经典例子

volatile 关键字的两层语义

方式一:变量不使用 volatile 修饰

public class VolatileTest extends Thread {
    private static boolean flag = false;

    public void run() {
        while (!flag) ;
    }

    public static void main(String[] args) throws Exception {
        new VolatileTest().start();
        Thread.sleep(2000);
        flag = true;
    }
}

方式二:变量使用 volatile 修饰

public class VolatileTest extends Thread {
    private static volatile boolean flag = false;

    public void run() {
        while (!flag) ;
    }

    public static void main(String[] args) throws Exception {
        new VolatileTest().start();
        Thread.sleep(2000);
        flag = true;
    }
}

运行结果
方式一:线程不会结束

方式二:线程会结束

public class TestMain {
    public static volatile boolean flag = true;

    public static void main(String[] args) throws InterruptedException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                }
                System.out.println(Thread.currentThread().getName() + "线程停止,死循环被打开");
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                flag = false;
                System.out.println(Thread.currentThread().getName() + "修改 flag 为" + flag);
            }
        }).start();

        Thread.sleep(Integer.MAX_VALUE);
    }
}

public class RunThread extends Thread {
    /** volatile */
    private volatile boolean isRunning = true;

    private void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    public void run() {
        System.out.println("进入 run() 方法中...");
        while (isRunning == true) {
            // doSomething()
        }
        System.out.println("线程结束了...");
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread myThread = new RunThread();
        myThread.start();
        Thread.sleep(3000);
        myThread.setRunning(false);
        System.out.println("isRunning 的值已经设置为了 false");
        Thread.sleep(1000);
        System.out.println(myThread.isRunning);
    }
}

public class RunThread extends Thread {
    /** volatile */
    private boolean isRunning = true;

    private void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    public void run() {
        System.out.println("进入 run() 方法中...");
        while (isRunning == true) {
            // doSomething()
        }
        System.out.println("线程结束了...");
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread myThread = new RunThread();
        myThread.start();
        Thread.sleep(3000);
        myThread.setRunning(false);
        System.out.println("isRunning 的值已经设置为了 false");
        Thread.sleep(1000);
        System.out.println(myThread.isRunning);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java中,volatile关键字通常用于以下两个场景: 1. 多线程之间的变量可见性: 当多个线程共享一个变量时,使用volatile关键字可以确保当一个线程修改了该变量的值后,其他线程能够立即看到最新的值。这样可以避免使用过期的缓存值,从而保证线程之间的通信和协同工作。例如: ```java class SharedData { volatile int count = 0; } class MyThread extends Thread { private SharedData sharedData; public MyThread(SharedData sharedData) { this.sharedData = sharedData; } public void run() { sharedData.count++; } } public class Main { public static void main(String[] args) throws InterruptedException { SharedData sharedData = new SharedData(); MyThread[] threads = new MyThread[10]; for (int i = 0; i < 10; i++) { threads[i] = new MyThread(sharedData); threads[i].start(); } for (int i = 0; i < 10; i++) { threads[i].join(); } System.out.println(sharedData.count); // 输出的结果应为10 } } ``` 2. 状态标志位: 当一个变量用于标识某个状态时,使用volatile关键字可以确保不同线程之间对该状态的可见性,从而实现线程之间的协作。例如: ```java class MyThread extends Thread { private volatile boolean isRunning = true; public void stopRunning() { isRunning = false; } public void run() { while (isRunning) { // 执行任务逻辑 } } } public class Main { public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.stopRunning(); thread.join(); } } ``` 在上述例子中,当isRunning被设置为false时,线程会停止运行。由于isRunning是volatile变量,所以对isRunning的修改对其他线程是可见的,从而能够确保线程可以及时停止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值