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

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

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

AtomicReference类的weakCompareAndSetRelease()方法用于将 AtomicReference 的值自动设置为 newValue,如果当前值等于作为参数传递的 expectedValue。此方法更新值并确保在此访问之后不会重新排序先前的加载和存储。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。

句法:

public final boolean
       weakCompareAndSetRelease(V expectedValue,
                                V newValue)

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

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

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

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

方案二:

// Java program to demonstrate
// AtomicReference.weakCompareAndSetRelease() 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 GFG");
  
        // apply weakCompareAndSetRelease()
        boolean result
            = ref.weakCompareAndSetRelease(
                "WELCOME TO GFG",
                "WELCOME TO GEEKS FOR 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#weakCompareAndSetRelease(V, V)