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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。