Java AtomicInteger updateAndGet()方法及示例
Java.AtomicInteger.updateAndGet() 方法是一个内置的方法,它通过对当前值应用指定的操作来更新对象的当前值。它接收一个IntUnaryOperator接口的对象作为参数,并将该对象中指定的操作应用于当前值。它返回更新后的值。
语法
public final int updateAndGet(IntUnaryOperator function)
参数: 该方法接受一个IntUnaryOperator 函数 作为参数。
它将给定的函数应用于对象的当前值。
返回值: 该函数返回当前对象的更新值。
演示该函数的例子 。
程序1:
// Java program to demonstrate the above function
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;
public class Demo {
public static void main(String[] args)
{
// Atomic Integer initialized with a value of 10
AtomicInteger ai = new AtomicInteger(10);
// Unary operator defined to negate the value
IntUnaryOperator unaryOperator = (x) -> - x;
System.out.println("Initial Value is " + ai);
// Function called and the unary operator
// is passed as an argument
int x = ai.updateAndGet(unaryOperator);
System.out.println("Updated value is " + x);
}
}
输出。
Initial Value is 10
Updated value is -10
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
极客教程