当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java AtomicReference getAndSet()用法及代码示例


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

用法:

public final V getAndSet?(V newValue)

参数:此方法接受newValue作为新值。


返回值:此方法返回AtomicReference的旧值。

以下示例程序旨在说明getAndSet()方法:
程序1:

// 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<Double> ref 
            = new AtomicReference<Double>(); 
  
        // 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()); 
    } 
}
输出:
OLD Value = 1234.0
NEW Value = 3213.0

程序2:

// 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<String> ref 
            = new AtomicReference<String>(); 
  
        // 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://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndSet(V)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 AtomicReference getAndSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。