Java中的 AtomicIntegerArray 累积AndGet() 方法及示例
Java.util.concurrent.atomic.AtomicIntegerArray.accumulateAndGet()是Java中的一个内置方法,它使用将给定函数应用于当前值和给定值的结果以原子方式更新索引 i 处的元素,并返回更新后的值。该函数应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,它可能会被重新应用。该函数应用索引 i 处的当前值作为其第一个参数,并将给定的更新作为第二个参数。
句法:
public final int accumulateAndGet(int i, int x, IntBinaryOperator accumulatorFunction)
参数:该函数接受三个参数:
返回值:该函数返回Integer中的更新值。
下面的程序说明了上述方法:
方案一:
// 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]
方案二:
// 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: Java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util。函数.IntBinaryOperator-