Java AtomicLongArray set()方法及示例

Java AtomicLongArray set()方法及示例

Java.util.concurrent.atomic.AtomicLongArray.set() 是Java中的一个内置方法,可以在AtomicLongArray的任何位置设置一个给定的值。该方法以AtomicLongArray的索引值为参数,更新该索引的值。这个方法不返回任何值。函数 set()getAndSet() 函数类似,但前者不返回任何值,而后者在设置该索引的新值之前返回给定索引的值。

语法

public final void set(int i, long newValue)

参数: 该函数需要两个参数。

  • i – 要进行更新的索引值。
  • newValue – 要在该索引处更新的新值。

返回值: 该函数不返回任何值。

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

程序1 :

// Java program that demonstrates
// the set() 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;
  
        // The new value to update at idx
        long val = 10;
  
        // Updating the value at
        // idx applying set
        arr.set(idx, val);
  
        // Displaying the AtomicLongArray
        System.out.println("The array after update : "
                           + arr);
    }
}

输出。

The array : [1, 2, 3, 4, 5]
The array after update : [10, 2, 3, 4, 5]

程序2

// Java program that demonstrates
// the set() 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;
  
        // The new value to update at idx
        long val = 100;
  
        // Updating the value at
        // idx applying set
        arr.set(idx, val);
  
        // 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, 100, 5]

参考资料:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLongArray.html#set-int-long-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程