关于“Java 并发实践”示例的问题
2022-09-01 18:27:31
我正在查看Brian Goetz的“Java Concurrency in Practice”中的代码示例。他说,这段代码可能会停留在无限循环中,因为“'ready'的值可能永远不会对读者线程可见”。我不明白这是怎么发生的...
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;
}
}