Java AtomicLongArray getAndDecrement()方法及示例
Java.util.concurrent.atomic.AtomicLongArray.getAndDecrement() 是Java中的一个内置方法,它可以将给定索引的值原子化地递减1。该方法获取AtomicLongArray的索引值,并返回该索引处存在的值,然后递减该索引处的值。 getAndDecrement() 函数与 decrementAndGet() 函数类似,但后一个函数返回递减后的值,而前一个则返回递减前的值。
语法
public final long getAndDecrement(int i)
参数: 该函数接受一个参数i,它是执行递减1操作的索引。
返回值: 该函数返回在索引处进行递减操作之前的值,该索引的单位是long。
以下程序说明了上述方法:
程序1 :
// Java program that demonstrates
// the getAndDecrement() 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;
// Decrementing the value at
// idx applying getAndDecrement
// and storing previous value
long prev = arr.getAndDecrement(idx);
// The previous value at idx
System.out.println("Value at index " + idx
+ " before decrement is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after decrement : "
+ arr);
}
}
输出。
The array : [1, 2, 3, 4, 5]
Value at index 3 before decrement is 4
The array after decrement : [1, 2, 3, 3, 5]
程序2
// Java program that demonstrates
// the getAndDecrement() function
import java.util.concurrent.atomic.AtomicLongArray;
public class GFG {
public static void main(String args[])
{
// Initializing an array
long a[] = { 10, 20, 30, 40, 50 };
// 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;
// Decrementing the value at
// idx applying getAndDecrement
// and storing previous value
long prev = arr.getAndDecrement(idx);
// The previous value at idx
System.out.println("Value at index " + idx
+ " before decrement is "
+ prev);
// Displaying the AtomicLongArray
System.out.println("The array after decrement : "
+ arr);
}
}
输出。
The array : [10, 20, 30, 40, 50]
Value at index 0 before decrement is 10
The array after decrement : [9, 20, 30, 40, 50]
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLongArray.html#getAndDecrement-int-