2012-03-30 30 views
4

如何在AtomicInteger變量中執行「check-then-act」?
I.e.什麼是最安全/最好的方法來檢查這種變量的值第一個和inc/dec取決於結果?
例如(高級別)
if(count < VALUE) count++; //原子級使用AtomicInteger安全地使用AtomicInteger首先檢查

+1

http://stackoverflow.com/questions/4818699/practical-uses-for-atomicinteger – user219882 2012-03-30 11:26:50

+0

@Tomas:我沒有看到一個答案在你link.Only如何使用it.How可以我原子地做一個check-then-act? – Jim 2012-03-30 11:31:12

回答

10

您需要編寫一個循環。假設count是你AtomicInteger參考,你會寫是這樣的:

while(true) 
{ 
    final int oldCount = count.get(); 
    if(oldCount >= VALUE) 
     break; 
    if(count.compareAndSet(oldCount, oldCount + 1)) 
     break; 
} 

上面會循環,直到:(1)你的if(count < VALUE)條件未得到滿足;或(2)count成功遞增。使用compareAndSet執行增量操作可以保證當我們設置新值時,count的值仍然是oldCount(因此仍然小於VALUE)。

0

如果你使用Java 8,你可以像這樣解決它。它是線程安全的並且是以原子方式執行的。

AtomicInteger counter = new AtomicInteger(); 
static final int COUNT = 10; 

public int incrementUntilLimitReached() { 
    return counter.getAndUpdate((n -> (n < COUNT) ? n + 1 : n)); 
}