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

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

Java中的 AtomicLongArray decrementAndGet() 方法及示例

Java.util.concurrent.atomic.AtomicLongArray.decrementAndGet()是Java中的一种内置方法,它以原子方式将给定索引处的元素递减一个。该方法将索引值和要添加的值作为参数,并在该索引处返回更新后的值。

句法:

public final long decrementAndGet(int i)

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

返回值:该函数返回long中的更新值。

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

// Java program that demonstrates
// the compareAndSet() 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 decrementAndGet
        arr.decrementAndGet(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, 3, 5]

方案二:

// Java program that demonstrates
// the compareAndSet() 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 = 0;
  
        // Updating the value at
        // idx applying decrementAndGet
        arr.decrementAndGet(idx);
  
        // Displaying the AtomicLongArray
        System.out.println("The array after update : "
                           + arr);
    }
}
输出:
The array : [1, 2, 3, 4, 5]
The array after update : [0, 2, 3, 4, 5]

参考:
https://docs.oracle.com/javase/8/docs/api/java Java