📜  Java的LongAccumulator getThenReset() 方法和示例

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

Java的LongAccumulator getThenReset() 方法和示例

Java的.LongAccumulator.getThenReset()是在Java()一个内置的方法,该方法等效于效果得到(),随后复位。首先,它获取当前值,然后重置该值。

句法:

public long getThenReset()

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

返回值:此方法返回重置前的值。

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



程序一

// Program to demonstrate the getThenReset() method
  
import java.lang.*;
import java.util.concurrent.atomic.LongAccumulator;
  
public class GFG {
    public static void main(String args[])
    {
        LongAccumulator num = new LongAccumulator(Long::sum, 0L);
  
        // accumulate operation on num
        num.accumulate(42);
        num.accumulate(10);
  
        num.get();
        // before getThenReset the value is
        System.out.println(" the old value is: " + num);
        ;
  
        // getThenResets current value
        num.getThenReset();
  
        // Print after getThenReset operation
        System.out.println(" the current value is: " + num);
    }
}
输出:
the old value is: 52
 the current value is: 0

方案二

// Program to demonstrate the getThenReset() method
  
import java.lang.*;
import java.util.concurrent.atomic.LongAccumulator;
  
public class GFG {
    public static void main(String args[])
    {
        LongAccumulator num = new LongAccumulator(Long::sum, 0L);
  
        // accumulate operation on num
        num.accumulate(2);
        num.accumulate(1);
  
        num.get();
        // before getThenReset the value is
        System.out.println(" the old value is: " + num);
          
  
        // getThenResets current value
        num.getThenReset();
  
        // Print after getThenReset operation
        System.out.println(" the current value is: " + num);
    }
}
输出:
the old value is: 3
the current value is: 0

参考:https://docs.oracle.com/javase/8/docs/api/的Java/util/concurrent/atomic/LongAccumulator.html#getThenReset-