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

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

  • 相关阅读:
    检查使用的端口
    time is always agains us
    检查使用的端口
    dreque问题一例
    查看重定向的输出
    安装VSS时,Um.dat may be corrupt
    修改网卡ip
    redis install on ubuntu/debian
    上火了
    学这么多技术是为什么
  • 原文地址:https://www.cnblogs.com/wk-missQ1/p/14746929.html
Copyright © 2020-2023  润新知