📌  相关文章
📜  Java中的 AtomicIntegerArray getAndDecrement() 方法及示例

📅  最后修改于: 2022-05-13 01:55:01.124000             🧑  作者: Mango

Java中的 AtomicIntegerArray getAndDecrement() 方法及示例

Java.util.concurrent.atomic.AtomicIntegerArray.getAndDecrement()是Java中的一种内置方法,它以原子方式将给定索引处的值减一。此方法获取 AtomicIntegerArray 的索引值并返回该索引处的值,然后递减该索引处的值。函数getAndDecrement()decrementAndGet()类似,但后者函数返回递减后的值,而前者返回递减前的值。

句法:

public final int getAndDecrement(int i)

参数:该函数接受一个参数i ,它是执行减一操作的索引。

返回值:该函数在int中的索引处返回减量操作之前的值。

下面的程序说明了上述方法:
方案一:

// Java program that demonstrates
// the getAndDecrement() 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;
  
        // Decrementing the value at
        // idx applying getAndDecrement
        // and storing previous value
        int prev = arr.getAndDecrement(idx);
  
        // The previous value at idx
        System.out.println("Value at index " + idx
                           + " before decrement is "
                           + prev);
  
        // Displaying the AtomicIntegerArray
        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.AtomicIntegerArray;
  
public class GFG {
    public static void main(String args[])
    {
        // Initializing an array
        int a[] = { 10, 20, 30, 40, 50 };
  
        // 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;
  
        // Decrementing the value at
        // idx applying getAndDecrement
        // and storing previous value
        int prev = arr.getAndDecrement(idx);
  
        // The previous value at idx
        System.out.println("Value at index " + idx
                           + " before decrement is "
                           + prev);
  
        // Displaying the AtomicIntegerArray
        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/AtomicIntegerArray.html#getAndDecrement(int)