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

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

Java中的 AtomicReferenceArray compareAndExchangeRelease() 方法及示例

AtomicReferenceArray类的compareAndExchangeRelease()方法用于将 AtomicReferenceArray 的索引 i 的值自动设置为 newValue,如果称为见证值的 AtomicReferenceArray 对象的索引 i 处的当前值等于预期值。此方法将返回见证值,该值与预期值相同。此方法更新值并确保在此访问之后不会重新排序先前的加载和存储。

句法:

public final boolean
       compareAndExchangeRelease(
           int i, E expectedValue, E newValue)

参数:此方法接受:

  • i是执行操作的 AtomicReferenceArray 的索引,
  • expectedValue是期望值和
  • newValue是要设置的新值。

返回值:该方法返回见证值,如果成功则与预期值相同。

下面的程序说明了 compareAndExchangeRelease() 方法:
方案一:

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

方案二:

// Java program to demonstrate
// compareAndExchangeRelease() method
  
import java.util.concurrent.atomic.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create an atomic reference object.
        AtomicReferenceArray ref
            = new AtomicReferenceArray(3);
  
        // set some value
        ref.set(0, "GFG");
        ref.set(1, "JS");
  
        // apply compareAndExchangeRelease()
        String oldV1
            = ref.compareAndExchangeRelease(
                0, "GFG",
                "GEEKS FOR GEEKS");
        String oldV2
            = ref.compareAndExchangeRelease(
                1, "JS",
                "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));
    }
}
输出:

参考: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#compareAndExchangeRelease(int, E, E)