Java AtomicIntegerArray updateAndGet()方法及示例
Java.util.concurrent.atomic.AtomicIntegerArray.updateAndGet() 是Java中的一个内置方法,在对AtomicIntegerArray的任何给定索引的值应用一个给定的更新函数后,更新该索引的值。该方法以AtomicIntegerArray的索引值和更新函数为参数,通过对该值应用更新函数来更新该索引的值。该函数应该是无副作用的,因为当试图更新由于线程之间的争夺而失败时,它可能被重新应用。
语法
public final int updateAndGet(int i, IntegerUnaryOperator updateFunction)
参数: 该函数接受两个参数。
- i : 是要进行更新的索引。
- updateFunction:这是一个单一参数的更新函数,告诉你要做什么更新。
返回值: 该函数返回一个int值,这是应用指定的更新函数后的值。
以下程序说明了上述方法:
程序1 :
// Java program that demonstrates
// the updateAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.IntUnaryOperator;
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;
// Declaring the updateFunction
IntUnaryOperator squaredFunction = (l) -> l * l;
// Updating the value at idx
// applying updateFunction
arr.updateAndGet(idx, squaredFunction);
// 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, 25]
程序2
// Java program that demonstrates
// the updateAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.IntUnaryOperator;
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 = 3;
// Declaring the updateFunction
IntUnaryOperator cubeFunction = (l) -> l * l * l;
// Updating the value at idx
// applying updateFunction
arr.updateAndGet(idx, cubeFunction);
// 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, 64, 5]
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#updateAndGet-int-java.util.function.IntUnaryOperator-
极客教程