Java AtomicLongArray decrementAndGet()方法及示例

Java AtomicLongArray decrementAndGet()方法及示例

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

语法

public final long decrementAndGet(int i)

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

返回值: 该函数返回更新的值,其单位为长。

以下程序说明了上述方法:

程序1 :

// 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]

程序2

// 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/util/concurrent/atomic/AtomicLongArray.html#decrementAndGet-int-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程