public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
Run Code Online (Sandbox Code Playgroud)
我发现increment方法在循环块中起作用.为什么我们不能在没有任何循环的情况下计算结果?什么是它?
如果另一个线程的到来改变的值AtomicInteger之间int current = get()和compareAndSet(current, next),则compareAndSet调用将失败.使用循环可确保永远不会发生这种可能性.
compareAndSet如果另一个线程增加或以其他方式修改AtomicInteger当前线程正在递增的调用,则调用可能返回falseAtomicInteger
current = get()AtomicIntegernext = current + 1if(compareAndSet(current, next))在步骤4,调用compareAndSet将返回false并将AtomicInteger保持不变,因为current将不匹配当前值AtomicInteger(由于在步骤2中已修改它的另一个线程); 因此该方法循环并再次尝试