Java AtomicInteger和Math.max
我试图在一个循环中获得计算值的最大值,我希望它是线程安全的。所以我决定使用AtomicInteger和Math.max,但是我找不到一个解决方案,所以这个操作可以被认为是原子的Java AtomicInteger和Math.max,java,thread-safety,atomic,Java,Thread Safety,Atomic,我试图在一个循环中获得计算值的最大值,我希望它是线程安全的。所以我决定使用AtomicInteger和Math.max,但是我找不到一个解决方案,所以这个操作可以被认为是原子的 AtomicInteger value = new AtomicInteger(0); // Having some cycle here... { Integer anotherCalculatedValue = ...; value.set(Math.max(value.get(), anothe
AtomicInteger value = new AtomicInteger(0);
// Having some cycle here... {
Integer anotherCalculatedValue = ...;
value.set(Math.max(value.get(), anotherCalculatedValue));
}
return value.get()
问题是我做了两个操作,因此不是线程安全的。我怎样才能解决这个问题?唯一的方法是使用
同步
如果Java 8可用,您可以使用:
AtomicInteger value = new AtomicInteger(0);
Integer anotherCalculatedValue = ...;
value.getAndAccumulate(anotherCalculatedValue, Math::max);
根据遗嘱:
以原子方式使用以下结果更新当前值:
将给定函数应用于当前值和给定值,
返回上一个值
这正是我需要的。我想知道活动线程的最大数量,所以我把它放在run()方法的开头(末尾有一个减量):
public void run(){int actNow=activeCount.incrementAndGet();maxActive.getAndAccumulate(actNow,Math::max);