在《Java并发编程实践》一书中,有一个样例让我感到困惑:
public class Novisibility {
private static boolean ready;
private static int number;
private static class ReaderThread implements Runnable {
public void run() {
while (!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) {
System.out.println("0");
new Thread(new ReaderThread()).run();
System.out.println("1");
number = 42;
System.out.println("2");
ready = true;
System.out.println("3");
}
}
我可以理解重新排序会导致循环永远不会中断,但我无法理解为什么“1”、“2”和“3”从未打印到控制台。有人能帮忙吗?