volatile的正确使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qfzhangwei/article/details/79417864
    private static volatile boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        String s = number2CN(10000001);
        System.out.println(s);
        Thread workThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (!stop) {//如果不是volatile修饰,将会发生指令重排 if(!stop) while(true)
                    i++;
                    try {
                        System.out.println("----over");
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {

                    }
                }
            }
        });
        workThread.start();
        TimeUnit.SECONDS.sleep(3);
        stop = true;

        System.out.println("----over");
    }
volatile的正确使用:一个线程写,一个变量读共享变量时,需要 HB(线程可见性)&&禁止指令重排优化

猜你喜欢

转载自blog.csdn.net/qfzhangwei/article/details/79417864