【发布时间】:2018-09-08 19:07:11
【问题描述】:
为什么当方法get() 被标记为同步时,尽管字段value 不是易失性,但这段代码成功完成?如果没有同步,它会在我的机器上无限期地运行(如预期的那样)。
public class MtApp {
private int value;
/*synchronized*/ int get() {
return value;
}
void set(int value) {
this.value = value;
}
public static void main(String[] args) throws Exception {
new MtApp().run();
}
private void run() throws Exception {
Runnable r = () -> {
while (get() == 0) ;
};
Thread thread = new Thread(r);
thread.start();
Thread.sleep(10);
set(5);
thread.join();
}
}
【问题讨论】:
-
如果没有正确同步,程序结果是不确定的。程序可以正确运行和完成,也可以不正确,这完全取决于 JVM 实现的突发奇想(并且该实现可能随时更改)。
标签: java multithreading synchronized non-volatile