当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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



相关用法


注:本文由纯净天空筛选整理自CharchitKapoor大神的英文原创作品 AtomicInteger updateAndGet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。