當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。