Java中的 AtomicLong accumulateAndGet() 方法及示例
Java.AtomicLong.accumulateAndGet()方法是一个内置方法,它通过对当前值和作为参数传递的值应用指定的操作来更新对象的当前值。它需要 long 作为其参数和 LongBinaryOperator 接口的对象,并将对象中指定的操作应用于值。它返回更新的值。
句法:
public final long accumulateAndGet(long y,
LongBinaryOperator function)
参数:此方法接受一个 long 值y和一个 LongBinaryOperator函数作为参数。它将给定函数应用于对象的当前值和值 y。
返回值:函数返回当前对象的更新值。
示例来演示函数。
Java
// Java program to demonstrate
// AtomicLong accumulateAndGet() method
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongBinaryOperator;
public class Demo {
public static void main(String[] args)
{
// AtomicLong initialized with a value of 555
AtomicLong atomicLong = new AtomicLong(555);
// Binary operator defined
// to calculate the product
LongBinaryOperator binaryOperator
= (x, y) -> x * y;
System.out.println("Initial Value is "
+ atomicLong);
// Function called and the binary operator
// is passed as an argument
long value
= atomicLong
.accumulateAndGet(555, binaryOperator);
System.out.println("Updated value is "
+ value);
}
}
输出:
Initial Value is 555
Updated value is 308025
参考: https: Java/util/concurrent/atomic/AtomicLong.html