多线程读写变量

请输入图片描述

线程A正在修改value。线程B正在读,这里读的就是过期的数据了。

只有给get,set同时加上同步才可以保证读到的不是过期数据。不明白,为什么get,set同时加上同步可以保证不出现这种情况?

继续往下看,好像明白一点,共享变量在公共的锁中是相互可见的。

阅读 6.1k
3 个回答
新手上路,请多包涵

加了同步也不能保证读到非过期的数据,问题不在这里。同步的作用是不会读到不完整的数据,这才是互斥的原因,int的更新未必是原子操作。

AtomicInteger,不需要synchronized,这种类型的一旦开始,就一直运行到结束,中间不会有任何Context switch

参见Synchronized Methods:

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

也就是说加锁的第二个作用是保证了内存壁垒。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题