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

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

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

AtomicReferenceArray类的getOpaque()方法用于返回此 AtomicReferenceArray 对象的索引 i 处元素的值,该对象具有 VarHandle.getOpaque(Java.lang.Object…) 指定的内存效应。这个 VarHandle.getOpaque(Java.lang.Object…) 方法处理操作时不保证相对于其他线程的内存排序效果。

句法:

public final E getOpaque(int i)

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

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

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

// Java program to demonstrate
// AtomicReferenceArray.getOpaque() method
  
import java.util.concurrent.atomic.*;
  
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, 987);
        array.set(1, 988);
        array.set(2, 989);
        array.set(3, 986);
  
        // get and print the value
        // using getOpaque method
        for (int i = 0; i < 4; i++) {
  
            int value = array.getOpaque(i);
            System.out.println("value at "
                               + i + " = "
                               + value);
        }
    }
}
输出:

方案二:

// Java program to demonstrate
// AtomicReferenceArray.getOpaque() method
  
import java.util.concurrent.atomic.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a array of Strings
        String[] names
            = { "AMAN", "AMAR", "SURAJ" };
  
        // create an atomic reference object.
        AtomicReferenceArray array
            = new AtomicReferenceArray(names);
  
        // get and print the value
        // using getOpaque method
        for (int i = 0; i < array.length(); i++) {
  
            String value = array.getOpaque(i);
            System.out.println("value at "
                               + i + " = "
                               + value);
        }
    }
}
输出:

参考资料: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#getOpaque(int)