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

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

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

AtomicReference类的compareAndExchangeAcquire()方法用于原子地将值设置为 newValue 到 AtomicReference 对象,如果称为见证值的 AtomicReference 对象的当前值等于预期值并返回见证值。此方法使用与 memory_order_acquire 排序兼容的内存排序效果交换值。

句法:

public final V compareAndExchangeAcquire(V expectedValue,
                                         V newValue)

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

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

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

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

方案二:

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

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