AtomicInteger在循环中计算

xyz*_*xyz 0 java atomic

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方法在循环块中起作用.为什么我们不能在没有任何循环的情况下计算结果?什么是它?

Jef*_*rey 6

如果另一个线程的到来改变的值AtomicInteger之间int current = get()compareAndSet(current, next),则compareAndSet调用将失败.使用循环可确保永远不会发生这种可能性.


Zim*_*oot 6

compareAndSet如果另一个线程增加或以其他方式修改AtomicInteger当前线程正在递增的调用,则调用可能返回falseAtomicInteger

  1. 当前线程调用 current = get()
  2. 另一个线程修改了 AtomicInteger
  3. 当前线程调用 next = current + 1
  4. 当前线程调用 if(compareAndSet(current, next))

在步骤4,调用compareAndSet将返回false并将AtomicInteger保持不变,因为current将不匹配当前值AtomicInteger(由于在步骤2中已修改它的另一个线程); 因此该方法循环并再次尝试