當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。