CAS????
????CAS?????compare and set????д??????????set????????????б仯???????????????2???丳???
??????????????????????
????if(a==b) {
????a++;
????}
??????????????????a++??a???????????????a++????????????????????????????????£?a?????????????????????????????????????????CAS???????????????????????

 

int expect = a;
if(a.compareAndSet(expect??a+1)) {
doSomeThing1();
} else {
doSomeThing2();
}

???????????a??????????a++??????С?
?????????????д????a!=expect???a++??????У????????????????a++??????????????????????while???

 

while(true) {
int expect = a;
if (a.compareAndSet(expect?? a + 1)) {
doSomeThing1();
return;
} else {
doSomeThing2();
}
}


?????????????д???????????????????????a++???????????????????????????
???????
????java.util.concurrent.atomic???м???????????????CAS????????AtomicInteger????????????????????????????

 

public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current?? newValue))
return current;
}
}


????getAndSet????JDK????е???????????????????????????????????????????????δ?????????compareAndSet???????compareAndSet??????????
????public final boolean compareAndSet(int expect?? int update) {
????return unsafe.compareAndSwapInt(this?? valueOffset?? expect?? update);
????}
?????????????????????Unsafe???CAS?????????
????????????a++??????????????

 

public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current?? next))
return current;
}
}