简体   繁体   English

java线程可见性

[英]java thread visibility

When I read the " java concurrency in practice " c03, I was confused by the following program: 当我读到“ 实践中的java并发 ”c03时,我对以下程序感到困惑:

public class NoVisibility { 
    private static boolean ready; 
    private static int number; 

    private static class ReaderThread extends Thread { 
        public void run() { 
            while (!ready) 
                Thread.yield(); 
            System.out.println(number); 
        } 
    } 

    public static void main(String[] args) { 
        new ReaderThread().start(); 
        number = 42; 
        ready = true; 
    } 
}

Because of the reordering and thread visibility, the loop may never stop, or the output may be zero, but I have tried many times, and the output is always 42. All the reason is I'm too lucky? 由于重新排序和线程可见性,循环可能永远不会停止,或输出可能为零,但我已尝试多次,输出始终为42.所有原因是我太幸运了?

All the reason is I'm too lucky? 所有的原因是我太幸运了?

Not necessarily. 不必要。 It will depend on your processor architecture and JVM implementation too. 它还取决于您的处理器架构和JVM实现。 That's one of the problems with subtle memory model issues: they can be very hard to reproduce in the wild. 这是微妙的记忆模型问题的一个问题:它们很难在野外重现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM