Java中的 AtomicLongArray 累积AndGet() 方法及示例
Java.util.concurrent.atomic.AtomicLongArray.accumulateAndGet()是Java中的一个内置方法,它使用将给定函数应用于当前值和给定值的结果以原子方式更新索引 i 处的元素,并返回更新后的值。该函数应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,它可能会被重新应用。该函数应用索引 i 处的当前值作为其第一个参数,并将给定的更新作为第二个参数。
句法:
public final long accumulateAndGet(int i, long x, LongBinaryOperator accumulatorFunction)
参数:该函数接受三个参数:
返回值:该函数返回long中的更新值。
下面的程序说明了上述方法:
方案一:
// Java program that demonstrates
// the accumulateAndGet() function
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.function.LongBinaryOperator;
public class GFG {
public static void main(String args[])
{
// Initializing an array
long a[] = { 1, 2, 3, 4, 5 };
// Initializing an AtomicLongArray with array a
AtomicLongArray arr = new AtomicLongArray(a);
// Displaying the AtomicLongArray
System.out.println("The array : " + arr);
// Index where update is to be made
int idx = 4;
// Value to make operation with value at idx
long x = 5;
// Declaring the accumulatorFunction
LongBinaryOperator add = (u, v) -> u + v;
// Updating the value at idx
// applying accumulatorFunction
arr.accumulateAndGet(idx, x, add);
// Displaying the AtomicLongArray
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.AtomicLongArray;
import java.util.function.LongBinaryOperator;
public class GFG {
public static void main(String args[])
{
// Initializing an array
long a[] = { 17, 22, 33, 44, 55 };
// Initializing an AtomicLongArray with array a
AtomicLongArray arr = new AtomicLongArray(a);
// Displaying the AtomicLongArray
System.out.println("The array : " + arr);
// Index where update is to be made
int idx = 0;
// Value to make operation with value at idx
long x = 6;
// Declaring the accumulatorFunction
LongBinaryOperator sub = (u, v) -> u - v;
// Updating the value at idx
// applying accumulatorFunction
arr.accumulateAndGet(idx, x, sub);
// Displaying the AtomicLongArray
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 Java。函数.LongBinaryOperator-