Java中的 AtomicReference 累积AndGet() 方法及示例
AtomicReference类的accumulateAndGet()方法用于使用将给定 accumulatorFunction 应用于当前值和给定值的结果以原子方式更新 AtomicReference 的当前值,并返回更新后的值。 accumulatorFunction 应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,它可能会被重新应用。
句法:
public final E accumulateAndGet(E x,
BinaryOperator accumulatorFunction)
参数:此方法接受:
- x是更新后的值,并且
- accumulatorFunction是两个参数的无副作用函数。
返回值:该方法返回更新后的值。
下面的程序说明了 accumulateAndGet() 方法:
方案一:
// 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 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);
}
}
输出:
方案二:
// 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 ref
= new AtomicReference("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: Java Java )