[英]Why is the write to non-volatile visible to the main-thread?
想象一下下面的程序。
class Main {
static class Whatever {
int x = 0;
}
public static void main(String[] args) {
Whatever whatever = new Whatever();
Thread t = new Thread(() -> {
whatever.x = 1;
});
t.start();
try {
t.join();
}
catch (InterruptedException e) {
}
System.out.println(whatever.x);
}
}
主线程已缓存whatever
,并且x
设置为0
。 另一个线程启动,缓存whatever
并将缓存的x
设置为1
。
output 是
1
所以主线程已经看到了写入。 这是为什么?
为什么对共享缓存进行了写入,为什么主线程使其缓存无效以从共享缓存中读取? 为什么我在这里不需要volatile
?
因为主线程加入它。 参见 JLS 中的 17.4.5:
线程中的所有操作都发生在任何其他线程从该线程上的 join() 成功返回之前。
顺便说一句,没有发生之前并不一定意味着某些东西不可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.