想象以下程序。
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
。
输出为
1
因此主线程已经看到了写入。为什么会这样?
为什么对共享缓存进行写操作,为什么主线程使它的缓存无效以从共享缓存中读取?为什么我在这里不需要volatile
?
由于连接了主线程。看到JLS中的17.4.5:
一个线程中的所有动作发生-在任何其他线程成功从该线程上的join()返回之前。