Nic*_*rio 3 java concurrency thread-safety
我正在研究Java Concurrency in Practice,并解释了为什么下面的代码片段很糟糕:
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)
此代码可能会打印0或永久循环.虽然很容易理解为什么NoVisibility可以打印0而不是42(由于重新排序问题),我对无限循环有点困惑.
在这段代码中,可能出现无限循环的实际场景是什么?
ready设置为时,循环停止true.并ready设置为true通过主线程.但由于该ready字段不是volatile,循环线程可能会继续看到缓存的值:false.
该volatile关键字保证读取volatile字段的所有线程实际上都会看到任何其他线程存储在该字段中的最后一个值.没有volatile,你没有这个保证.