Java中的 AtomicLongArray getAndDecrement() 方法及示例
Java.util.concurrent.atomic.AtomicLongArray.getAndDecrement()是Java中的一种内置方法,它以原子方式将给定索引处的值减一。此方法获取 AtomicLongArray 的索引值并返回该索引处的值,然后递减该索引处的值。函数getAndDecrement()与decrementAndGet()类似,但后者函数返回递减后的值,而前者返回递减前的值。
句法:
public final long getAndDecrement(int i)
参数:该函数接受一个参数i ,它是执行减一操作的索引。
返回值:该函数在long中的索引处返回减量操作之前的值。
下面的程序说明了上述方法:
方案一:
// 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]
方案二:
// 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: Java/util/concurrent/atomic/AtomicLongArray.html#getAndDecrement-int-