Java中的 AtomicReference set() 方法及示例
AtomicReference类的set()方法用于设置此 AtomicReference 对象的值,该对象具有读取的内存语义,就好像该变量被声明为 volatile 类型的变量一样。
句法:
public final void set(V newValue)
参数:此方法接受 newValue,这是要设置的新值。
返回值:此方法不返回任何内容。
下面的程序说明了 set() 方法:
方案一:
// Java program to demonstrate
// AtomicReference.set() method
import java.util.concurrent.atomic.AtomicReference;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object
// which stores Integer.
AtomicReference ref
= new AtomicReference();
// set some value using set method
ref.set(13243546);
// print value
System.out.println("value 1 = " + ref.get());
}
}
输出:
value 1 = 13243546
方案二:
// Java program to demonstrate
// AtomicReference.set() method
import java.util.concurrent.atomic.AtomicReference;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object
// which stores String.
AtomicReference ref
= new AtomicReference();
// set some value
ref.set("WELCOME TO GEEKS FOR GEEKS");
// print value
System.out.println("V = " + ref.get());
}
}
输出:
V = WELCOME TO GEEKS FOR GEEKS
参考资料: https: Java/util/concurrent/atomic/AtomicReference.html#set(V)