📌  相关文章
📜  Java中的 AtomicReferenceArray get() 方法及示例

📅  最后修改于: 2022-05-13 01:54:56.549000             🧑  作者: Mango

Java中的 AtomicReferenceArray get() 方法及示例

AtomicReferenceArray类的get()方法用于返回此 AtomicReferenceArray 对象的索引 i 处元素的值,该对象具有读取的内存语义,就好像索引的变量被声明为 volatile 类型的变量一样。

句法:

public final E get(int i)

参数:此方法接受索引 i以获取值。

返回值:此方法返回索引 i 处的当前值

下面的程序说明了 get() 方法:
方案一:

// 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 array
            = new AtomicReferenceArray(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

方案二:

// 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 array
            = new AtomicReferenceArray(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: Java/util/concurrent/atomic/AtomicReferenceArray.html#get(int)