原子操作 [英] AtomicLong operations
问题描述
我需要执行以下操作:
//平均,总计,已过的是Long的
average =((total * average)+ elapsed)/(++ total);但是我想使用 AtomicLong
p>
这是我想要的,但我不太会得到,如果是正确的:
average.set(((total.get()* average.get())+ elapsed)/ total.getAndIncrement());
如何判断这是否正确?
解决方案据推测,您正在使用AtomicLong,因为这些数字正在同时访问。因为你有两个数字,你在同一个语句中使用get和incrementAndGet,我不认为AtomicLong是正确的选择。
我发现AtomicXXX在许多情况下非常有帮助。但在这里,我想你需要做的艰难的方式。让你的数字简单的长私有变量,创建一个保护对象,然后确保在任何时候访问数字的同步保护对象。
我认为你唯一可以确定这些操作是真正原子的方式。
I need to perform the following operation:
// average, total, elapsed are Long's
average = ( ( total * average ) + elapsed ) / (++total);
But I want to use AtomicLong
This is what I'm trying but I don't quite get if it is correct:
average.set( (( total.get() * average.get() ) + elapsed) / total.getAndIncrement() );
How can I tell if this is correct?
解决方案 Presumably you are using AtomicLong because these numbers are being accessed concurrently. Since you have two numbers involved and you are using both a get and incrementAndGet in the same statement, I don't think AtomicLong is the right choice.
I have found AtomicXXX to be very helpful in many situations. But here, I think you need to do it the hard way. Make your numbers simple "long" private variables, create a guard object, then make sure to synchronize on the guard object any time you access the numbers.
I think that is the only way you can be certain that these operations are truly atomic.
这篇关于原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!