java - 如果 getter 被标记为同步,为什么这段代码会完成?
问题描述
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();
}
}
解决方案
同步力this.value = value
发生在之前 get()
。
它确保更新值的可见性。
没有同步,就没有这样的保证。它可能有效,也可能无效。
推荐阅读
- python-3.x - Python Selenium switch_to.frame() 不起作用
- spring-boot - 访问 Zuul 配置管理时出错
- java - Java泛型声明有点复杂?
- cakephp - 考虑时间范围获取行数
- r - 如何根据数据框名称中间的模式获取数据框列表?
- javascript - IONIC/Angular:HTML 不显示来自 ts 文件的信息
- javascript - 如何在 React Native 中从绑定到平面列表的不同组件调用函数
- bash - 从自动机中的脚本路径更改运行
- asp.net-core - 从视图中禁用电子邮件发件人
- java - 当客户端身份验证在码头服务器上失败时,浏览器上出现空白屏幕