如果当前值小于给定值,如何更新 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);
关于java - 如何根据条件更新原子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29626524/