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

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

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

AtomicReference类的compareAndSet()方法用于原子地将 value 设置为 newValue 到 AtomicReference 对象,如果 AtomicReference 对象的当前值等于 expectedValue 并且如果操作成功则返回 true 否则返回 false。此方法使用设置的内存语义更新值,就好像变量被声明为易失性一样。

句法:

public final V compareAndSet(V expectedValue,
                             V newValue)

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

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

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

// Java program to demonstrate
// AtomicReference.compareAndSet() 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(987654321L);
  
        // apply compareAndSet()
        boolean response
            = ref.compareAndSet(1234L,
                                999999L);
  
        // print value
        System.out.println(" Value is set = "
                           + response);
    }
}
输出:
Value is set = false

方案二:

// Java program to demonstrate
// AtomicReference.compareAndSet() 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 compareAndSet()
        boolean response
            = ref.compareAndSet(
                "Geeks For Geeks",
                "GFG");
  
        // print value
        System.out.println(" Value is set = "
                           + response);
    }
}
输出:
Value is set = true

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