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


Java AtomicReferenceArray get()用法及代碼示例


AtomicReferenceArray類的get()方法用於返回此AtomicReferenceArray對象的索引i處元素的值,該元素具有讀取的內存語義,就像將index的變量聲明為volatile類型的變量一樣。

用法:

public final E get(int i)

參數:此方法接受索引i以獲取值。


返回值:此方法返回索引i處的當前值。

以下示例程序旨在說明get()方法:
程序1:

// Java program to demonstrate 
// AtomicReferenceArray.get() method 
  
import java.util.concurrent.atomic.AtomicReferenceArray; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create an atomic reference array object 
        // which stores Integer. 
        AtomicReferenceArray<Integer> array 
            = new AtomicReferenceArray<Integer>(5); 
  
        // set some value in array 
        array.set(0, 12); 
        array.set(1, 13); 
        array.set(2, 14); 
        array.set(3, 15); 
  
        // get and print the value using get method 
        for (int i = 0; i < 4; i++) { 
  
            int value = array.get(i); 
            System.out.println("value at "
                               + i + " = " + value); 
        } 
    } 
}
輸出:
value at 0 = 12
value at 1 = 13
value at 2 = 14
value at 3 = 15

程序2:

// Java program to demonstrate 
// AtomicReferenceArray.get() method 
  
import java.util.concurrent.atomic.AtomicReferenceArray; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create an atomic reference array object 
        // which stores String. 
        AtomicReferenceArray<String> array 
            = new AtomicReferenceArray<String>(5); 
  
        // set some value in array 
        array.set(0, "AMAN"); 
        array.set(1, "AMAR"); 
  
        // get and print the value using get method 
        for (int i = 0; i < 2; i++) { 
  
            String value = array.get(i); 
            System.out.println("value at "
                               + i + " = " + value); 
        } 
    } 
}
輸出:
value at 0 = AMAN
value at 1 = AMAR

參考: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReferenceArray.html#get(int)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReferenceArray get() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。