get()
尽管字段值不是易失性的,为什么当方法被标记为同步时此代码成功完成?如果没有同步,它会在我的机器上无限期地运行(如预期的那样)。
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();
}
}