2012-03-30 62 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)); 
} 
相关问题