有关并发编程里的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;
    }
}

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

 

posted @ 2021-05-08 23:28  WK_BlogYard  阅读(35)  评论(0编辑  收藏  举报