我们先来看一下AtomicInteger类的getAndIncrement的源代码:
public final int getAndIncrement() {
for (;;) {
int current = get(); // 取得AtomicInteger里存储的数值
int next = current + 1; // 加1
if (compareAndSet(current, next)) // 调用compareAndSet执行原子更新操作
return current;
}
}
这段代码写的很巧妙: