Java中的AtomicReferenceArray accumulateAndGet()方法及示例
AtomicReferenceArray类的accumulateAndGet()方法用于以将给定 accumulatorFunction 应用于当前值和给定值的结果原子地更新 AtomicReferenceArray 的索引 i 处的元素,并返回更新后的值。 accumulatorFunction 应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,它可能会被重新应用。该函数应用索引 i 处的当前值作为其第一个参数,并将给定的更新作为第二个参数。
句法:
public final E accumulateAndGet(int i, E x,
BinaryOperator accumulatorFunction)
参数:此方法接受:
- i是执行操作的 AtomicReferenceArray 的索引,接受,
- x是更新后的值,并且
- accumulatorFunction是两个参数的无副作用函数。
返回值:该方法返回更新后的值。
下面的程序说明了 accumulateAndGet() 方法:
方案一:
// Java program to demonstrate
// accumulateAndGet() method
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
// an array
Integer a[] = { 123, 1232, 1433, 134, 13415, 1343 };
// AtomicReferenceArray with array
AtomicReferenceArray array
= new AtomicReferenceArray<>(a);
// Print AtomicReferenceArray
System.out.println(
"The AtomicReferenceArray before update\n: "
+ array);
// Index and Value to apply accumulateAndGet
int index = 2;
int E = 343;
// Declaring the accumulatorFunction
// applying function to add value as string
BinaryOperator add
= (u, v)
-> u.toString()
+ v.toString();
// apply accumulateAndGet()
array.accumulateAndGet(index, E, add);
// print AtomicReferenceArray
System.out.println(
"The AtomicReferenceArray "
+ "after update \n: "
+ array);
}
}
输出:
方案二:
// Java program to demonstrate
// accumulateAndGet() method
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
// an array
String a[] = { "GFG", "JS" };
// AtomicReferenceArray with array
AtomicReferenceArray arra
= new AtomicReferenceArray<>(a);
// Print AtomicReferenceArray
System.out.println(
"The AtomicReferenceArray"
+ " before update \n: "
+ array);
// Index and Value to apply accumulateAndGet
int index = 1;
String E = " PYTHON";
// Declaring the accumulatorFunction
// applying function to add value as string
BinaryOperator add
= (u, v)
-> u.toString()
+ " and "
+ v.toString();
// apply accumulateAndGet()
array.accumulateAndGet(index, E, add);
// print AtomicReferenceArray
System.out.println(
"The AtomicReferenceArray"
+ " after update \n: "
+ array);
}
}
输出:
参考资料: https://docs.oracle.com/javase/10/docs/api/java /util/concurrent/atomic/AtomicReferenceArray.html#accumulateAndGet(int, E, Java Java 函数)