📜  Java中的 DoubleAdder sumThenReset() 方法及示例

📅  最后修改于: 2022-05-13 01:54:24.446000             🧑  作者: Mango

Java中的 DoubleAdder sumThenReset() 方法及示例

Java.DoubleAdder.sumThenReset()是Java中的一个内置方法,相当于 sum() then reset() 方法,即首先计算有效和,然后将值重置以保持值为零。创建类的对象时,其初始值为零。

句法:

public double sumThenReset()

参数:此方法不接受任何参数。

返回值:该方法返回总和。

下面的程序说明了上述方法:

程序 1

// Program to demonstrate the sumThenReset() method
  
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
  
public class GFG {
    public static void main(String args[])
    {
        DoubleAdder num = new DoubleAdder();
  
        // add operation on num
        num.add(42);
        num.add(10);
  
        // sum operation on num
        num.sum();
  
        // Print after sum operation
        System.out.println(" the value after sum is: " + num);
  
        // sumThenReset operation on variable num
        num.sumThenReset();
  
        // Print after sumThenReset operation
        System.out.println("the current value is: " + num);
    }
}
输出:
the value after sum is: 52.0
the current value is: 0.0

方案二

// Program to demonstrate the sumThenReset() method
  
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
  
public class GFG {
    public static void main(String args[])
    {
        DoubleAdder num = new DoubleAdder();
  
        // add operation on num
        num.add(254);
  
        // sum operation on num
        num.sum();
  
        // Print after sum operation
        System.out.println(" the value after sum is: " + num);
  
        // sumThenReset operation on variable num
        num.sumThenReset();
  
        // Print after sumThenReset operation
        System.out.println("the current value is: " + num);
    }
}
输出:
the value after sum is: 254.0
the current value is: 0.0

参考:https: Java/util/concurrent/atomic/DoubleAdder.html#sumThenReset–