Java AtomicIntegerArray incrementAndGet()方法及示例
Java.util.concurrent.atomic.AtomicIntegerArray.incrementAndGet() 是Java中的一个内置方法,它可以将AtomicIntegerArray的任何索引的值原子化地增加1。该方法以AtomicIntegerArray的索引值为参数,增加该索引的值并返回增加后的值。函数 incrementAndGet() 与 getAndIncrement() 函数类似,但前者返回增量后的值,而后者则返回增量操作前的值。
语法
public final int incrementAndGet(int i)
参数: 该函数接受一个参数i,它是进行增量操作的索引。
返回值: 该函数返回增量操作后的值,该值为整数。
以下程序说明了上述方法。
程序1 :
// Java program that demonstrates
// the incrementAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
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 operation is performed
int idx = 3;
// Updating the value at
// idx applying incrementAndGet
arr.incrementAndGet(idx);
// 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, 5, 5]
程序2
// Java program that demonstrates
// the incrementAndGet() function
import java.util.concurrent.atomic.AtomicIntegerArray;
public class GFG {
public static void main(String args[])
{
// Initializing an array
int a[] = { 11, 12, 13, 14, 15 };
// Initializing an AtomicIntegerArray with array a
AtomicIntegerArray arr = new AtomicIntegerArray(a);
// Displaying the AtomicIntegerArray
System.out.println("The array : " + arr);
// Index where operation is performed
int idx = 0;
// Updating the value at
// idx applying incrementAndGet
arr.incrementAndGet(idx);
// Displaying the AtomicIntegerArray
System.out.println("The array after update : "
+ arr);
}
}
输出。
The array : [11, 12, 13, 14, 15]
The array after update : [12, 12, 13, 14, 15]
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#incrementAndGet(int)
极客教程