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);
}
}
輸出:
相關用法
- Java AtomicLong accumulateAndGet()用法及代碼示例
- Java AtomicIntegerArray accumulateAndGet()用法及代碼示例
- Java AtomicLongArray accumulateAndGet()用法及代碼示例
- Java AtomicInteger accumulateAndGet()用法及代碼示例
- Java AtomicReferenceArray accumulateAndGet()用法及代碼示例
- Java AtomicReference get()用法及代碼示例
- Java AtomicReference set()用法及代碼示例
- Java AtomicReference compareAndSet()用法及代碼示例
- Java AtomicReference getAndAccumulate()用法及代碼示例
- Java AtomicReference updateAndGet()用法及代碼示例
- Java AtomicReference lazySet()用法及代碼示例
- Java AtomicReference weakCompareAndSet()用法及代碼示例
- Java AtomicReference setPlain()用法及代碼示例
- Java AtomicReference compareAndExchangeAcquire()用法及代碼示例
- Java AtomicReference getAndUpdate()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReference accumulateAndGet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。