我正在尝试来自 JCIP 的示例,并且下面的程序不应该工作,但即使我执行它说 20 次它总是工作,这意味着ready
并且number
正在变得可见,即使它应该在这种情况下
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(Runtime.getRuntime().availableProcessors());
//Number of Processor is 4 so 4+1 threads
new Thread(new ReaderThread()).start();
new Thread(new ReaderThread()).start();
new Thread(new ReaderThread()).start();
new Thread(new ReaderThread()).start();
new Thread(new ReaderThread()).start();
number = 42;
ready = true;
}
}
在我的机器上它总是打印
4 -- Number of Processors
42
42
42
42
42
According to Listing 3.1 of JCIP It should sometimes print 0 or should never terminate it also suggest that there is no gaurantee that ready and number written by main thread will be visible to reader thread
更新 我在所有线程分层后在主线程中添加了 1000ms 睡眠仍然相同的输出。我知道程序坏了我希望它会这样