AtomicReference類的getAndAccumulate()方法用於原子地更新AtomicReference的當前值,並將給定的accumulatorFunction應用於當前值和給定值,並返回先前的值。 accumulatorFunction應該沒有副作用,因為當嘗試更新由於線程之間的爭用而失敗時,可能會重新應用accumulatorFunction。應用該函數時,將當前值作為其第一個參數,並將給定的update作為第二個參數。
用法:
public final E getAndAccumulate(E x, BinaryOperator<E> accumulatorFunction)
參數:此方法接受:
- x這是更新的值,
- accumulatorFunction這是兩個參數的無副作用函數。
返回值:此方法返回prevoius值。
以下示例程序旨在說明getAndAccumulate()方法:
程序1:
// Java program to demonstrate
// AtomicReference.getAndAccumulate() method
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
// AtomicReference with value
AtomicReference<Integer> ref
= new AtomicReference<>(3456);
// Value to apply getAndAccumulate
int x = 45654;
// Declaring the accumulatorFunction
// applying function to add value as string
BinaryOperator add
= (u, v) -> u.toString() + v.toString();
// apply getAndAccumulate()
int value = ref.getAndAccumulate(x, add);
// 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.getAndAccumulate() method
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
// AtomicReference with value
AtomicReference<String> ref
= new AtomicReference<String>("GFG ");
// Value to apply getAndAccumulate
String x = "Welcome";
// Declaring the accumulatorFunction
// applying function to add value as string
BinaryOperator add
= (u, v) -> v + " to " + u;
// apply getAndAccumulate()
String previousValue
= ref.getAndAccumulate(x, add);
// print AtomicReference
System.out.println(
"The AtomicReference previous value:"
+ previousValue);
}
}
輸出:
相關用法
- Java AtomicInteger getAndAccumulate()用法及代碼示例
- Java AtomicReferenceArray getAndAccumulate()用法及代碼示例
- Java AtomicLongArray getAndAccumulate()用法及代碼示例
- Java AtomicReference get()用法及代碼示例
- Java AtomicReference set()用法及代碼示例
- Java AtomicReference setPlain()用法及代碼示例
- Java AtomicReference setOpaque()用法及代碼示例
- Java AtomicReference updateAndGet()用法及代碼示例
- Java AtomicReference getAndUpdate()用法及代碼示例
- Java AtomicReference compareAndSet()用法及代碼示例
- Java AtomicReference getAcquire()用法及代碼示例
- Java AtomicReference compareAndExchangeRelease()用法及代碼示例
- Java AtomicReference accumulateAndGet()用法及代碼示例
- Java AtomicReference compareAndExchangeAcquire()用法及代碼示例
- Java AtomicReference toString()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReference getAndAccumulate() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。