網(wǎng)上看到的例子
/**
* @author zhengbinMac
*/
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
@Override
public void run() {
while(!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
NoVisibility可能會(huì)持續(xù)循環(huán)下去,因?yàn)樽x線(xiàn)程可能永遠(yuǎn)都看不到ready的值。甚至NoVisibility可能會(huì)輸出0,因?yàn)樽x線(xiàn)程可能看到了寫(xiě)入ready的值,但卻沒(méi)有看到之后寫(xiě)入number的值,這種現(xiàn)象被稱(chēng)為“重排序”。
我的問(wèn)題是:難道static變量也會(huì)被緩存到cpu cache中嗎?感覺(jué)很詭異啊。。。
volitile關(guān)鍵字問(wèn)題
慕尼黑5688855
2019-03-01 10:35:11