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


Java AtomicReferenceArray getAndSet()用法及代碼示例


AtomicReferenceArray類的getAndSet()方法用於原子地將AtomicReferenceArray對象的索引i的值設置為newValue,該值作為參數傳遞並返回AtomicReferenceArray對象的舊值,具有由VarHandle.getAndSet(java.lang .Object…).VarHandle.getAndSet(java.lang.Object…)指定將變量作為設置的內存語義,就像將該變量聲明為volatile一樣。

用法:

public final E getAndSet(int i, E newValue)

參數:此方法接受:


  • i這是執行操作的AtomicReferenceArray的索引,
  • newValue 這是要設置的新值。

返回值:此方法返回索引i的舊值。

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

// Java program to demonstrate 
// AtomicReferenceArray.getAndSet() method 
  
import java.util.concurrent.atomic.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create an atomic reference object. 
        AtomicReferenceArray<Integer> ref 
            = new AtomicReferenceArray<Integer>(3); 
  
        // set some value 
        ref.set(0, 1234); 
        ref.set(1, 4322); 
  
        // apply getAndSet() 
        int oldV1 = ref.getAndSet(0, 8913); 
        int oldV2 = ref.getAndSet(1, 6543); 
  
        // print 
        System.out.println("Old value at index 0:"
                           + oldV1); 
        System.out.println("New value at index 0:"
                           + ref.get(0)); 
        System.out.println("Old value at index 1:"
                           + oldV2); 
        System.out.println("New value at index 1:"
                           + ref.get(1)); 
    } 
}
輸出:
Old value at index 0:1234
New value at index 0:8913
Old value at index 1:4322
New value at index 1:6543

程序2:

// Java program to demonstrate 
// AtomicReferenceArray.getAndSet() method 
  
import java.util.concurrent.atomic.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create an atomic reference object. 
        AtomicReferenceArray<String> ref 
            = new AtomicReferenceArray<String>(3); 
  
        // set some value 
        ref.set(0, "GFG"); 
        ref.set(1, "JS"); 
  
        // apply getAndSet() 
        String oldV1 
            = ref.getAndSet(0, "GEEKS FOR GEEKS"); 
        String oldV2 
            = ref.getAndSet(1, "JAVA SCRIPT"); 
  
        // print 
        System.out.println( 
            "Old value at index 0:"
            + oldV1); 
        System.out.println( 
            "New value at index 0:"
            + ref.get(0)); 
        System.out.println( 
            "Old value at index 1:"
            + oldV2); 
        System.out.println( 
            "New value at index 1:"
            + ref.get(1)); 
    } 
}
輸出:
Old value at index 0:GFG
New value at index 0:GEEKS FOR GEEKS
Old value at index 1:JS
New value at index 1:JAVA SCRIPT

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReferenceArray.html#getAndSet(int, E)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReferenceArray getAndSet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。