Ste*_*sky 11 java concurrentmodification atomicinteger
如何更新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;
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*per 19
如果您使用的是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);
Run Code Online (Sandbox Code Playgroud)
如果我没有 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;
}
Run Code Online (Sandbox Code Playgroud)
从OP的代码中,它将被这样调用:
AtomicInteger ai = new AtomicInteger(0);
int threadInt = ...
// Update ai atomically, but only if the current value is less than threadInt
setIfIncreases(ai, threadInt);
Run Code Online (Sandbox Code Playgroud)