这是一个简单的例子:
private long counter = 0;
// note this method is NOT synchronized
// this will be called by thread A
public void increment() { counter++; }
// note this method IS synchronized
// this will be called by thread B
public synchronized long value() { return counter; }
所以我只想获得一个好的值counter
,而不是 cpu 缓存中的卡住值,因为该变量是非易失性的。目标是不使计数器易失,因此它不会影响执行增量的线程 A,而只会影响线程 B,我不在乎,当它读取变量时。
只是为了记录,我计划counter
在线程 A 已经完成时从线程 B 读取值......