Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I read the "java concurrency in practice" c03, I was confused by the following program:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
632 views
Welcome To Ask or Share your Answers For Others

1 Answer

All the reason is I'm too lucky?

Not necessarily. It will depend on your processor architecture and JVM implementation too. That's one of the problems with subtle memory model issues: they can be very hard to reproduce in the wild.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...