线程A正在修改value。线程B正在读,这里读的就是过期的数据了。
只有给get,set同时加上同步才可以保证读到的不是过期数据。不明白,为什么get,set同时加上同步可以保证不出现这种情况?
继续往下看,好像明白一点,共享变量在公共的锁中是相互可见的。
线程A正在修改value。线程B正在读,这里读的就是过期的数据了。
只有给get,set同时加上同步才可以保证读到的不是过期数据。不明白,为什么get,set同时加上同步可以保证不出现这种情况?
继续往下看,好像明白一点,共享变量在公共的锁中是相互可见的。
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.
也就是说加锁的第二个作用是保证了内存壁垒。
8 回答6.8k 阅读
4 回答1k 阅读✓ 已解决
1 回答2.5k 阅读✓ 已解决
4 回答475 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
2 回答651 阅读✓ 已解决
2 回答1.2k 阅读
加了同步也不能保证读到非过期的数据,问题不在这里。同步的作用是不会读到不完整的数据,这才是互斥的原因,int的更新未必是原子操作。