多线程读写变量

https://img.mukewang.com/5cb443800001cd4a08000203.jpg

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

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

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


qq_笑_17
浏览 562回答 3
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.也就是说加锁的第二个作用是保证了内存壁垒。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java