11

AtomicInteger如果当前值小于给定值,如何更新?这个想法是:

AtomicInteger ai = new AtomicInteger(0);
...
ai.update(threadInt); // this call happens concurrently
...
// inside AtomicInteger atomic operation
synchronized {
    if (ai.currentvalue < threadInt)
        ai.currentvalue = threadInt;
}
4

3 回答 3

23

如果您使用的是 Java 8,则可以使用 中的新更新方法之一AtomicInteger,您可以传递 lambda 表达式。例如:

AtomicInteger ai = new AtomicInteger(0);

int threadInt = ...

// Update ai atomically, but only if the current value is less than threadInt
ai.updateAndGet(value -> value < threadInt ? threadInt : value);
于 2015-04-14T11:58:01.093 回答
3

如果您没有 Java 8,则可以使用这样的 CAS 循环:

while (true) {
    int currentValue = ai.get();
    if (newValue > currentValue) {
        if (ai.compareAndSet(currentValue, newValue)) {
            break;
        }
    }
}
于 2015-04-14T12:02:16.847 回答
3

如果我没有 Java 8,我可能会创建一个实用程序方法,例如:

public static boolean setIfIncreases(AtomicInteger ai, int newValue) {
    int currentValue;
    do {
        currentValue = ai.get();
        if (currentValue >= newValue) {
            return false;
        } 
     } while (!ai.compareAndSet(currentValue, newValue));
     return true;
}

然后从 OP 的代码中调用它:

AtomicInteger ai = new AtomicInteger(0);

int threadInt = ...

// Update ai atomically, but only if the current value is less than threadInt
setIfIncreases(ai, threadInt);
于 2018-03-22T09:56:21.913 回答