首页 > 多线程读写变量

多线程读写变量

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

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

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


参见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.

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


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


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

【热门文章】
【热门文章】