我試圖從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睡眠後,將所有線程的輸出保持相同。 我知道程序是壞了,我希望它表現得這樣
爲什麼你認爲它不應該工作? –
'private'變量對內部類可見。沒有理由不應該這樣做。 –
JCIP書清單3.1建議它應該打印0或永遠運行。 –