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