Java中的 AtomicLongArray getAndAccumulate() 方法及示例
Java.util.concurrent.atomic.AtomicLongArray.getAndAccumulate()是Java中的一个内置方法,它在将给定函数应用于当前值和给定值后,用结果原子更新 AtomicLongArray 的任何索引处的值,返回前一个值.此方法接受要执行操作的 AtomicLongArray 的索引、执行操作的值和累加器函数作为参数。该函数应用索引处的当前值作为其第一个参数,并将给定的更新作为第二个参数。累加器函数应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,它可能会被重新应用。 getAndAccumulate()函数与accumulateAndGet()函数类似,但前者返回更新前的值,而后者返回更新后的值。
句法:
public final long getAndAccumulate(int i, long x, LongBinaryOperator accumulatorFunction)
参数:该函数接受三个参数:
返回值:函数返回更新前的值,在long中。
下面的程序说明了上述方法:
方案一:
// Java program that demonstrates
// the getAndAccumulate() 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 getAndAccumulate
long prev = arr.getAndAccumulate(idx, x, add);
// The previous value at idx
System.out.println("Value at index " + idx
+ " before update is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after update : "
+ arr);
}
}
输出:
The array : [1, 2, 3, 4, 5]
Value at index 4 before update is 5
The array after update : [1, 2, 3, 4, 10]
方案二:
// Java program that demonstrates
// the getAndAccumulate() 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 = 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 getAndAccumulate
long prev = arr.getAndAccumulate(idx, x, sub);
// The previous value at idx
System.out.println("Value at index " + idx
+ " before update is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after update : "
+ arr);
}
}
输出:
The array : [1, 2, 3, 4, 5]
Value at index 0 before update is 1
The array after update : [-5, 2, 3, 4, 5]
参考:
https://docs.oracle.com/javase/8/docs/api/java Java。函数.LongBinaryOperator-