cas:內存值v,舊的預期值a,要修改的新值b。只有當內存值v與舊的預期值a相等時纔會改成新的值b,否則則判定暫時有其他線程在做操作,不是線程安全的。內部沒有使用synchronized來實現,使用了volitile原語去直接讀內存中的值,沒有實現操作的原子性,只保證了操作的可見性,在atomic等類中被使用。
private volatile int value;
public final int get() {
return value;
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}