Java中的 AtomicReferenceArraylazySet() 方法及示例
AtomicReferenceArray类的lazySet()方法用于将索引i 处的元素的值设置为newValue。索引 i 和 newValue 都作为参数传递给该方法。此方法使用 VarHandle.setRelease(Java.lang.Object...) 指定的内存效应设置值,以确保在此访问之后不会重新排序先前的加载和存储。
句法:
public final void lazySet(int i, E newValue)
参数:此方法接受:
- i是执行操作的 AtomicReferenceArray 的索引,
- newValue是要设置的新值。
返回值:此方法不返回任何内容。
下面的程序说明了lazySet() 方法:
方案一:
// Java program to demonstrate
// AtomicReferenceArray.lazySet() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReferenceArray ref
= new AtomicReferenceArray(3);
// set some value using lazySet() and print
ref.lazySet(0, 1234);
ref.lazySet(1, 4322);
ref.lazySet(2, 2345);
System.out.println("Value of index 0 = "
+ ref.get(0));
System.out.println("Value of index 1 = "
+ ref.get(1));
System.out.println("Value of index 2 = "
+ ref.get(2));
}
}
输出:
方案二:
// Java program to demonstrate
// AtomicReferenceArray.lazySet() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object
AtomicReferenceArray
HIMALAYAN_COUNTRY
= new AtomicReferenceArray(5);
// set some value
HIMALAYAN_COUNTRY.lazySet(0, "INDIA");
HIMALAYAN_COUNTRY.lazySet(1, "CHINA");
HIMALAYAN_COUNTRY.lazySet(2, "PAKISTAN");
HIMALAYAN_COUNTRY.lazySet(3, "BHUTAN");
HIMALAYAN_COUNTRY.lazySet(4, "NEPAL");
// print
for (int i = 0; i < 5; i++) {
System.out.println(
HIMALAYAN_COUNTRY.get(i));
}
}
}
输出:
参考资料: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#lazySet(int, E)