当我读到" 实践中的java并发 "c03时,我对以下程序感到困惑:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
由于重新排序和线程可见性,循环可能永远不会停止,或输出可能为零,但我已尝试多次,输出始终为42.所有原因是我太幸运了?
| 归档时间: |
|
| 查看次数: |
468 次 |
| 最近记录: |