Java AtomicLongArray getAndIncrement()方法及示例
Java.util.concurrent.atomic.AtomicLongArray.getAndIncrement() 是Java中的一个内置方法,它可以将AtomicLongArray的任何索引上的值原子化地增加1。该方法以AtomicLongArray的索引值为参数,返回递增前该索引的值,然后递增该索引的值。函数 getAndIncrement() 与 incrementAndGet() 函数类似,但前者返回增量前的值,而后者返回增量操作后的值。
语法
public final long getAndIncrement(int i)
参数: 该函数接受一个参数i,它是进行增量操作的索引。
返回值: 该函数返回更新前该索引的先前值,该值为long。
下面的程序说明了上述方法。
程序1 :
// Java program that demonstrates
// the getAndIncrement() 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 getAndIncrement
// and storing the previous value
long prev = arr.getAndIncrement(idx);
// Previous value at idx before update
System.out.println("Value at index " + idx
+ " before the update is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after update : "
+ arr);
}
}
输出。
The array : [11, 12, 13, 14, 15]
Value at index 0 before the update is 11
The array after update : [12, 12, 13, 14, 15]
程序2
// Java program that demonstrates
// the getAndIncrement() 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 = 3;
// Updating the value at
// idx applying getAndIncrement
// and storing the previous value
long prev = arr.getAndIncrement(idx);
// Previous value at idx before update
System.out.println("Value at index " + idx
+ " before the update is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after update : "
+ arr);
}
}
输出。
The array : [11, 12, 13, 14, 15]
Value at index 3 before the update is 14
The array after update : [11, 12, 13, 15, 15]
注意: 函数getAndIncrement()与incrementAndGet()相似,但后者的函数返回更新的值,而前者则返回更新后的先前值。
参考资料 :https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLongArray.html#getAndIncrement-int-