首頁  >  問答  >  主體

java - 如何理解AtomicInteger里的CAS操作?

下面这个方法,我不理解

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

为何要循环直到成功?如果这期间有另外的线程更改了value,导致compareAndSet()返回false,那这就表面已经不是原子性了吧,还继续重复有啥意义?

PHP中文网PHP中文网2744 天前638

全部回覆(1)我來回復

  • ringa_lee

    ringa_lee2017-04-18 10:51:42

    它只是要實現寫入操作不會被覆蓋掉,多線程情況下不會計算錯誤,如果按照你這麼想要實現原子性,只能使用鎖了,但是這樣效率會低。

    回覆
    0
  • 取消回覆