當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。