如果其当前值小于给定值,如何更新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;
}

最佳答案

如果您使用的是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);

10-07 22:07