Java AtomicLong updateAndGet()方法及示例

Java AtomicLong updateAndGet()方法及示例

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

语法

public final long updateAndGet(LongUnaryOperator function)

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

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

演示该函数的例子

// Java program to demonstrate
// AtomicLong updateAndGet() method
 
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongUnaryOperator;
 
public class Demo {
    public static void main(String[] args)
    {
        // AtomicLong initialized with a value of -20000
        AtomicLong al = new AtomicLong(-20000);
 
        // Unary operator defined to negate the value
        LongUnaryOperator unaryOperator = (x) -> - x;
 
        System.out.println("Initial Value is " + al);
 
        // Function called and the unary operator
        // is passed as an argument
        long x = al.updateAndGet(unaryOperator);
        System.out.println("Updated value is " + x);
    }
}

输出

Initial Value is -20000
Updated value is 20000

参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程