当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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-



相关用法


注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 AtomicLongArray set() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。