Volatile 可见性例子

2020-04-05  本文已影响0人  wuli白
public class Volatile {

    static boolean stop = false;
    public static void main(String[] args) throws InterruptedException {

       new Thread(() -> {
            while (!stop) {
            }
            System.out.println("I am done");
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stop = true;
        }).start();
        Thread.sleep(3000L);
    }
}

场景:设置一个标识位为volatile,防止多次启动

上一篇下一篇

猜你喜欢

热点阅读