Java AtomicLong accumulateAndGet()方法及示例

Java AtomicLong accumulateAndGet()方法及示例

Java.AtomicLong.accumulateAndGet() 方法是一个内置的方法,它通过对当前值和作为参数传递的值应用指定的操作来更新对象的当前值。它接收一个long作为其参数和一个LongBinaryOperator接口的对象,并将该对象中指定的操作应用于数值。它返回更新后的值。

语法

public final long accumulateAndGet(long y, 
              LongBinaryOperator function)

参数: 该方法接受一个长值 y 和一个LongBinaryOperator 函数 作为参数。 它将给定的函数应用于对象的当前值和值y。

返回值: 该函数返回当前对象的更新值。

演示该函数的例子

// 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://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程