Java AtomicIntegerArray accumulateAndGet()方法及示例
Java.util.concurrent.atomic.AtomicIntegerArray.accumulateAndGet() 是java中的一个内置方法,它用给定函数对当前值和给定值的应用结果原子地更新索引i处的元素,并返回更新值。该函数应该是无副作用的,因为当试图更新时,由于线程之间的争夺,它可能被重新应用。该函数以索引i处的当前值为第一参数,以给定的更新值为第二参数来应用。
语法
public final int accumulateAndGet(int i, int x, IntBinaryOperator accumulatorFunction)
参数: 该函数接受三个参数。
- i – 要进行更新的索引。
- x – 要对i处的值进行操作的值。
- accumulatorFunction – 一个有两个参数的无副作用的函数。
返回值: 该函数返回更新后的值,该值为整数。
以下程序说明了上述方法:
程序 1 :
// Java program that demonstrates
// the accumulateAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.IntBinaryOperator;
public class GFG {
public static void main(String args[])
{
// Initializing an array
int a[] = { 1, 2, 3, 4, 5 };
// Initializing an AtomicIntegerArray with array a
AtomicIntegerArray arr = new AtomicIntegerArray(a);
// Displaying the AtomicIntegerArray
System.out.println("The array : " + arr);
// Index where update is to be made
int idx = 4;
// Value to make operation with value at idx
int x = 5;
// Declaring the accumulatorFunction
IntBinaryOperator add = (u, v) -> u + v;
// Updating the value at idx
// applying accumulatorFunction
arr.accumulateAndGet(idx, x, add);
// Displaying the AtomicIntegerArray
System.out.println("The array after update : "
+ arr);
}
}
输出。
The array : [1, 2, 3, 4, 5]
The array after update : [1, 2, 3, 4, 10]
程序2
// Java program that demonstrates
// the accumulateAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.IntBinaryOperator;
public class GFG {
public static void main(String args[])
{
// Initializing an array
int a[] = { 17, 22, 33, 44, 55 };
// Initializing an AtomicIntegerArray with array a
AtomicIntegerArray arr = new AtomicIntegerArray(a);
// Displaying the AtomicIntegerArray
System.out.println("The array : " + arr);
// Index where update is to be made
int idx = 0;
// Value to make operation with value at idx
int x = 6;
// Declaring the accumulatorFunction
IntBinaryOperator sub = (u, v) -> u - v;
// Updating the value at idx
// applying accumulatorFunction
arr.accumulateAndGet(idx, x, sub);
// Displaying the AtomicIntegerArray
System.out.println("The array after update : "
+ arr);
}
}
输出。
The array : [17, 22, 33, 44, 55]
The array after update : [11, 22, 33, 44, 55]
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util.function.IntBinaryOperator-
极客教程