public class AtomicCompareAndSwap {
private int value;
public synchronized int getValue() {
return value;
}
//比较
public synchronized int compareAndSwap(int expectValue, int newValue) {
int oldValue = this.value;
if (expectValue == oldValue) {
this.value = newValue;
}
return oldValue;
}
//设置
public synchronized boolean compareAndSet(int expectValue, int newValue) {
return expectValue == compareAndSwap(expectValue, newValue);
}
}
AtomicCompareAndSwap a = new AtomicCompareAndSwap();
a.compareAndSet(0, 2);
System.out.println(a.getValue());
模拟CAS
最新推荐文章于 2022-10-13 10:16:23 发布