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


Java AtomicReference accumulateAndGet()用法及代碼示例


AtomicReference類的accumulateAndGet()方法用於原子地更新AtomicReference的當前值,並將給定的accumulatorFunction應用於當前值和給定值,並返回更新後的值。 accumulatorFunction應該沒有副作用,因為當嘗試更新由於線程之間的爭用而失敗時,可能會重新應用accumulatorFunction。

用法:

public final E accumulateAndGet(E x,
     BinaryOperator<E> accumulatorFunction)

參數:此方法接受:


  • x這是更新的值,
  • accumulatorFunction這是兩個參數的無副作用函數。

返回值:此方法返回更新的值。

以下示例程序旨在說明accumulateAndGet()方法:
程序1:

// Java program to demonstrate 
// AtomicReference.accumulateAndGet() method 
  
import java.util.concurrent.atomic.AtomicReference; 
import java.util.function.BinaryOperator; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // AtomicReference with value 
        AtomicReference<Integer> ref 
            = new AtomicReference<>(3456); 
  
        // Print AtomicReference 
        System.out.println( 
            "The AtomicReference before update:"
            + ref); 
  
        // Value to apply accumulateAndGet 
        int x = 45654; 
  
        // Declaring the accumulatorFunction 
        // applying function to add value as string 
        BinaryOperator add 
            = (u, v) -> u.toString() + v.toString(); 
  
        // apply accumulateAndGet() 
        ref.accumulateAndGet(x, add); 
  
        // print AtomicReference 
        System.out.println( 
            "The AtomicReference after update:"
            + ref); 
    } 
}
輸出:

程序2:

// Java program to demonstrate 
// AtomicReference.accumulateAndGet() method 
  
import java.util.concurrent.atomic.AtomicReference; 
import java.util.function.BinaryOperator; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
        // AtomicReference with value 
        AtomicReference<String> ref 
            = new AtomicReference<String>("GFG "); 
  
        // Print AtomicReference 
        System.out.println("The AtomicReference before update:"
                           + ref); 
  
        // Value to apply accumulateAndGet 
        String x = "Welcome"; 
  
        // Declaring the accumulatorFunction 
        // applying function to add value as string 
        BinaryOperator add 
            = (u, v) -> v + " to " + u; 
  
        // apply accumulateAndGet() 
        ref.accumulateAndGet(x, add); 
  
        // print AtomicReference 
        System.out.println( 
            "The AtomicReference after update:"
            + ref); 
    } 
}
輸出:

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#accumulateAndGet(V, java.util.function.BinaryOperator)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReference accumulateAndGet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。