Java – shared variables without synchronization

I read from Java concurrency in practice that it is not good to share variables in threads without synchronization However, for some examples with only one read thread and one write thread, I can't find its error From my point of view, the result of the following program will definitely terminate and print 42, because the readerthread can pass only when it is ready, which means that the number is 42 Can someone explain to me why I was wrong?

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;
    } 
}

Solution

Since ready is not volatile, there is no guarantee that readerthread will see that your main thread has changed it When you mark ready as volatile, all writes from one thread will be seen in other threads reading it

When communicating between threads, some kind of synchronization / visibility control is always required Whether it's volatile, use synchronized explicitly or use Java util. concurrent.* Class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>