[英]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.