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

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

Java中的 AtomicReference weakCompareAndSetPlain() 方法和示例

AtomicReference类的weakCompareAndSetPlain()方法用于将 AtomicReference 的值自动设置为 newValue,如果当前值等于作为参数传递的 expectedValue。此方法使用设置的内存语义更新值,就好像变量被声明为非易失性和非最终的。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。

句法:

public final boolean
       weakCompareAndSetPlain(V expectedValue,
                              V newValue)

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

返回值:如果成功,此方法返回true

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

// Java program to demonstrate
// AtomicReference.weakCompareAndSetPlain() 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(1234L);
  
        // apply weakCompareAndSetPlain()
        boolean result
            = ref.weakCompareAndSetPlain(
                1111L,
                999999L);
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
        System.out.println("Value = " + ref.get());
    }
}
输出:

方案二:

// Java program to demonstrate
// AtomicReference.weakCompareAndSetPlain() method
  
import java.util.concurrent.atomic.AtomicReference;
  
public class GFG {
    public static void main(String[] args)
    {
        // create an atomic reference object
        // which stores String.
        AtomicReference ref
            = new AtomicReference();
  
        // set some value
        ref.set("WELCOME TO GEEKS FOR GEEKS");
  
        // apply weakCompareAndSetPlain()
        boolean result
            = ref.weakCompareAndSetPlain(
                "WELCOME TO GEEKS FOR GEEKS",
                "GFG GEEKS");
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
        System.out.println("Value  = " + ref.get());
    }
}
输出:

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