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;
}
}
此代码可能会打印0或永久循环.
虽然很容易理解为什么NoVisibility可以打印0而不是42(由于重新排序问题),
我对无限循环有点困惑.
在这段代码中,可能出现无限循环的实际场景是什么?
解决方法:
当ready设置为true时,循环停止.并且主线程将ready设置为true.但由于ready字段不是volatile,循环线程可能会继续看到缓存的值:false.
volatile关键字保证读取volatile字段的所有线程实际上都会看到任何其他线程存储在该字段中的最后一个值.没有挥发性,你没有这个保证.
标签:java,concurrency,thread-safety
来源: https://codeday.me/bug/20190726/1540462.html