有关并发编程里的Volatile关键字的使用

2021/5/9 1:25:34

本文主要是介绍有关并发编程里的Volatile关键字的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.首先是展示一个因为Java的指令重排导致的问题,我们想要终止一个线程,但是主线程修改的值,子线程不可见。

public class VolatileDemo {
    public static boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            int i = 0;
            while (!stop) {
                i ++;
            }
            System.out.println("i=" + i);
        }).start();
        Thread.sleep(1000);
        stop = true;
    }
}

示例结果:并没有任何打印,原因是因为子线程并不知道主线程对值做了修改。

 

 2.那如何能终止这个线程?我们需要使用volatile关键字来对程序做一下修改,使得变量对子线程也可见

public class VolatileDemo {
    public static volatile boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            int i = 0;
            while (!stop) {
                i ++;
            }
            System.out.println("i=" + i);
        });
//        thread.interrupt();
        thread.start();
        Thread.sleep(1000);
        stop = true;
    }
}

实例结果:说明线程已经终止了。

 



这篇关于有关并发编程里的Volatile关键字的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程