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

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

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

Java.util.concurrent.atomic.AtomicLongArray.getAndIncrement()是Java中的一种内置方法,它以原子方式将 AtomicLongArray 的任何索引处的值加一。该方法将 AtomicLongArray 的索引值作为参数,返回递增前该索引处的值,然后递增该索引处的值。 getAndIncrement()函数与incrementAndGet()函数类似,但前者返回增量前的值,后者返回增量操作后的值。

句法:

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

返回值:该函数返回更新前该索引处的前一个值,该值位于long中。

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

方案一:

// Java program that demonstrates
// the getAndIncrement() function
  
import java.util.concurrent.atomic.AtomicLongArray;
  
public class GFG {
    public static void main(String args[])
    {
        // Initializing an array
        long a[] = { 11, 12, 13, 14, 15 };
  
        // 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 getAndIncrement
        // and storing the previous value
        long prev = arr.getAndIncrement(idx);
  
        // Previous value at idx before update
        System.out.println("Value at index " + idx
                           + " before the update is "
                           + prev);
  
        // Displaying the AtomicLongArray
        System.out.println("The array after update : "
                           + arr);
    }
}
输出:
The array : [11, 12, 13, 14, 15]
Value at index 0 before the update is 11
The array after update : [12, 12, 13, 14, 15]

方案二:

// Java program that demonstrates
// the getAndIncrement() function
  
import java.util.concurrent.atomic.AtomicLongArray;
  
public class GFG {
    public static void main(String args[])
    {
        // Initializing an array
        long a[] = { 11, 12, 13, 14, 15 };
  
        // 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 getAndIncrement
        // and storing the previous value
        long prev = arr.getAndIncrement(idx);
  
        // Previous value at idx before update
        System.out.println("Value at index " + idx
                           + " before the update is "
                           + prev);
  
        // Displaying the AtomicLongArray
        System.out.println("The array after update : "
                           + arr);
    }
}
输出:
The array : [11, 12, 13, 14, 15]
Value at index 3 before the update is 14
The array after update : [11, 12, 13, 15, 15]

注意: getAndIncrement()函数与 incrementAndGet()函数类似,但后者返回更新后的值,而前者返回更新后的先前值。

参考: https: Java/util/concurrent/atomic/AtomicLongArray.html#getAndIncrement-int-