美文网首页
Volatile 可见性例子

Volatile 可见性例子

作者: wuli白 | 来源:发表于2020-04-05 21:36 被阅读0次
    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,防止多次启动

    相关文章

      网友评论

          本文标题:Volatile 可见性例子

          本文链接:https://www.haomeiwen.com/subject/hrnpphtx.html