2015-04-14 90 views
6

如何更新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; 
} 
+0

请贴没有任何编译错误,即工作代码.. – SMA

+0

您发布的代码片段没有意义。你首先更新'ai'(不管你用.update()表示的意思),并且用新的检查值。 – SubOptimal

+1

这是一个很好的问题,它非常有意义。对于批评:OP不可能为此编写工作代码。如果他这样做了,他需要知道答案,所以他只能发布伪代码。 –

回答

11

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

如果您没有安装Java 8中,您可以使用CAS环这样的:

while (true) { 
    int currentValue = ai.get(); 
    if (newValue > currentValue) { 
     if (ai.compareAndSet(currentValue, newValue)) { 
      break; 
     } 
    } 
}