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

インクリメント メソッドがループ ブロック内で機能することがわかりました。ループせずに結果を計算できないのはなぜですか? それについての意味は何ですか?

4

4 に答える 4

6

現在のcompareAndSetスレッドAtomicIntegerAtomicInteger

  1. 現在のスレッド呼び出しcurrent = get()
  2. 別のスレッドがAtomicInteger
  3. 現在のスレッド呼び出しnext = current + 1
  4. 現在のスレッド呼び出しif(compareAndSet(current, next))

ステップ 4 で、への呼び出しcompareAndSetは false を返し、 の現在の値と一致しAtomicIntegerないため(ステップ 2 で別のスレッドがそれを変更したため)、 は変更されません。したがって、メソッドはループして再試行しますcurrentAtomicInteger

于 2013-07-18T19:31:51.707 に答える
1

別のスレッドが更新中の場合、compareAndSet は失敗する可能性があります。for(;;) は少し奇妙です。

これは楽観的ロックと呼ばれます。

于 2013-07-18T19:32:28.563 に答える