簡體   English   中英

AtomicInteger和Math.max

[英]AtomicInteger and Math.max

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

AtomicInteger value = new AtomicInteger(0);


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

return value.get()

問題是我做了兩個操作,因此不是線程安全的。 我怎么解決這個問題? 唯一的方法是使用synchronized

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

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

規范中將:

原子地使用將給定函數應用於當前值和給定值的結果更新當前值,返回先前的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM