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