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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。