经典共享变量不可见问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15037231/article/details/85784484
public class NoVisibility {

    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread {

        @Override
        public void run() {
            while (!ready) {
                Thread.yield();
            }
            System.out.println(number);
        }

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

问题现象:

NoVisibility could loop forever because the value of ready might never become visible to the reader thread. 
Even more strangely, NoVisibility could print zero because the write to ready might be made visible to the reader thread before the write to number, a phenomenon known as reordering. There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread even if 
the reordering is apparent to other threads. When the main thread writes first to number and then to done without synchronization, the reader thread could see those writes happen in the opposite order or not at all.

简译:

NoVisibility可能不会打印任何值,因为读线程可能永远看不到ready的值。一种更奇怪的现象是,NoVisibility可能会输出0,因为读线程可能看到了写入的ready的值,但是却没有看到之后写入的number的值。只要有数据在多个线程之间共享,就应该使用正确的同步。 

猜你喜欢

转载自blog.csdn.net/qq_15037231/article/details/85784484
今日推荐