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

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

Java中的 AtomicReference getAndSet() 方法及示例

AtomicReference类的getAndSet()方法用于以原子方式将 AtomicReference 对象的值设置为 newValue,该值作为参数传递并返回 AtomicReference 对象的旧值,具有 VarHandle.getAndSet(Java.lang. Object...).VarHandle.getAndSet(Java.lang.Object...) 指定该变量是句柄作为设置的内存语义,就好像该变量被声明为易失性一样。

句法:

public final V getAndSet?(V newValue)

参数:此方法接受新值newValue
返回值:此方法返回 AtomicReference 的旧值。
下面的程序说明了 getAndSet() 方法:
方案一:

Java
// Java program to demonstrate
// AtomicReference.getAndSet() method
 
import java.util.concurrent.atomic.AtomicReference;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create an atomic reference object.
        AtomicReference ref
            = new AtomicReference();
 
        // set some value
        ref.set(1234.00);
 
        // get and replace value
        double oldValue
            = ref.getAndSet((double)3213);
 
        // print
        System.out.println("OLD Value = "
                           + oldValue);
        System.out.println("NEW Value = "
                           + ref.get());
    }
}


Java
// Java program to demonstrate
// AtomicReference.getAndSet() method
 
import java.util.concurrent.atomic.AtomicReference;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create an atomic reference object.
        AtomicReference ref
            = new AtomicReference();
 
        // set some value
        ref.set("AtomicReference old value");
 
        // get and replace value
        String oldValue = ref.getAndSet(
            "AtomicReference new value");
 
        // print
        System.out.println("OLD Value = "
                           + oldValue);
        System.out.println("NEW Value = "
                           + ref.get());
    }
}


输出:
OLD Value = 1234.0
NEW Value = 3213.0

方案二:

Java

// Java program to demonstrate
// AtomicReference.getAndSet() method
 
import java.util.concurrent.atomic.AtomicReference;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create an atomic reference object.
        AtomicReference ref
            = new AtomicReference();
 
        // set some value
        ref.set("AtomicReference old value");
 
        // get and replace value
        String oldValue = ref.getAndSet(
            "AtomicReference new value");
 
        // print
        System.out.println("OLD Value = "
                           + oldValue);
        System.out.println("NEW Value = "
                           + ref.get());
    }
}
输出:
OLD Value = AtomicReference old value
NEW Value = AtomicReference new value

参考资料: https: Java/util/concurrent/atomic/AtomicReference.html#getAndSet(V)