2017-03-31 76 views
3

我試圖得到一個週期中的calculateValue的最大值,我希望它是線程安全的。所以我決定使用AtomicInteger和Math.max,但是我找不到一個解決方案,以便可以將操作視爲原子操作。AtomicInteger和Math.max

AtomicInteger value = new AtomicInteger(0); 


// Having some cycle here... { 
    Integer anotherCalculatedValue = ...; 
    value.set(Math.max(value.get(), anotherCalculatedValue)); 
} 

return value.get() 

問題是我做了兩個操作,因此不是線程安全的。我該如何解決這個問題?唯一的辦法是使用​​?

回答

4

如果你的Java 8可用,您可以使用:

AtomicInteger value = new AtomicInteger(0); 
Integer anotherCalculatedValue = ...; 
value.getAndAccumulate(anotherCalculatedValue, Math::max); 

specification將:

以原子更新與 結果的當前值應用給定函數爲當前和給定值, 返回以前的值。

+1

這正是我所需要的。我想知道有效線程的最大數量,所以我把它放在我run()方法的開始處(最後一個遞減): 'public void run() { int actNow = activeCount。 incrementAndGet(); maxActive.getAndAccumulate(actNow,Math :: max);' – user1683793