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


Java AtomicReference getAndUpdate()用法及代码示例


AtomicReference类的getAndUpdate()方法用于原子更新,该更新通过对当前值应用指定的updateFunction操作来更新AtomicReference的当前值。它以updateFunction接口的对象为参数,并将该对象中指定的操作应用于当前值。它返回先前的值。

用法:

public final V getAndUpdate(UnaryOperator<V> updateFunction)

参数:此方法接受updateFunction,它是没有副作用的函数。


返回值:此方法返回prevoius值。

以下示例程序旨在说明getAndUpdate()方法:
程序1:

// Java program to demonstrate 
// AtomicReference.getAndUpdate() method 
  
import java.util.concurrent.atomic.AtomicReference; 
import java.util.function.UnaryOperator; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // AtomicReference with value 
        AtomicReference<Integer> ref 
            = new AtomicReference<>(987654); 
  
        // Declaring the updateFunction 
        // applying function 
        UnaryOperator twoDigits 
            = (v) 
            -> v.toString() 
                   .substring(0, 2); 
  
        // apply getAndUpdate() 
        int value = ref.getAndUpdate(twoDigits); 
  
        // print AtomicReference 
        System.out.println( 
            "The AtomicReference previous value:"
            + value); 
        System.out.println( 
            "The AtomicReference new value:"
            + ref.get()); 
    } 
}
输出:

程序2:

// Java program to demonstrate 
// AtomicReference.getAndUpdate() method 
  
import java.util.concurrent.atomic.*; 
import java.util.function.UnaryOperator; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // AtomicReference with value 
        AtomicReference<String> ref 
            = new AtomicReference<>("welcome"); 
  
        // Declaring the updateFunction 
        // applying function 
        UnaryOperator twoDigits 
            = (v) -> v + " to gfg"; 
  
        // apply getAndUpdate() 
        String value 
            = ref.getAndUpdate(twoDigits); 
  
        // print AtomicReference 
        System.out.println( 
            "The AtomicReference previous value:"
            + value); 
        System.out.println( 
            "The AtomicReference new value:"
            + ref.get()); 
    } 
}
输出:

参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndUpdate(java.util.function.UnaryOperator)



相关用法


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