Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java AtomicInteger和Math.max_Java_Thread Safety_Atomic - Fatal编程技术网

Java 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和Math.max,但是我找不到一个解决方案,所以这个操作可以被认为是原子的

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);