Java中的 AtomicLongArray set() 方法及示例
Java.util.concurrent.atomic.AtomicLongArray.set()是Java中的一个内置方法,它在 AtomicLongArray 的任何位置设置给定值。此方法将 AtomicLongArray 的索引值作为参数并更新该索引处的值。此方法不返回任何值。函数set()类似于getAndSet()函数,但前者不返回任何值,而后者返回给定索引处的值,然后在该索引处设置新值。
句法:
public final void set(int i, long newValue)
参数:该函数有两个参数:
返回值:该函数不返回任何值。
下面的程序说明了上述方法:
方案一:
// 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]
方案二:
// 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 Java