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

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

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

AtomicReference类的compareAndExchangeRelease()方法用于原子地将值设置为 newValue 到 AtomicReference 对象,如果称为见证值的 AtomicReference 对象的当前值等于预期值并返回见证值。此方法更新值并确保在此访问之后不会重新排序先前的加载和存储。

句法:

public final V compareAndExchangeRelease(
                                  V expectedValue,
                                  V newValue)

参数:此方法接受期望值newValue ,这是要设置的新值。

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

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

// Java program to demonstrate
// AtomicReference.compareAndExchangeRelease() method
  
import java.util.concurrent.atomic.AtomicReference;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create an atomic reference object
        // which stores Integer.
        AtomicReference ref
            = new AtomicReference();
  
        // set some value
        ref.set(987654321L);
  
        // apply compareAndExchangeRelease()
        long oldValue
            = ref.compareAndExchangeRelease(
                987654321L,
                999999L);
  
        // print value
        System.out.println("Witness Value = "
                           + oldValue);
    }
}
输出:

方案二:

// Java program to demonstrate
// AtomicReference.compareAndExchangeRelease() 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("Geeks For Geeks");
  
        // apply compareAndExchangeRelease()
        String oldValue
            = ref.compareAndExchangeRelease(
                "Geeks For Geeks",
                "GFG");
  
        // print value
        System.out.println("Witness Value = "
                           + oldValue);
    }
}
输出:

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