Java中的 AtomicReference weakCompareAndSetVolatile() 方法及示例
AtomicReference类的weakCompareAndSetVolatile()方法用于将 AtomicReference 的值自动设置为 newValue,如果当前值等于作为参数传递的 expectedValue。此方法使用 VarHandle.weakCompareAndSet(Java.lang.Object…) 指定的记忆效应更新值。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。
句法:
public final boolean
weakCompareAndSetVolatile(V expectedValue,
V newValue)
参数:此方法接受期望值和newValue ,这是要设置的新值。
返回值:如果成功,此方法返回true 。
下面的程序说明了weakCompareAndSetVolatile() 方法:
方案一:
// Java program to demonstrate
// AtomicReference.weakCompareAndSetVolatile() 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(1234.00);
// apply weakCompareAndSetVolatile()
boolean result
= ref.weakCompareAndSetVolatile(124.00,
234.32);
// print value
System.out.println("Setting new value"
+ " is successful = "
+ result);
System.out.println("Value = " + ref.get());
}
}
输出:
方案二:
// Java program to demonstrate
// AtomicReference.weakCompareAndSetVolatile() 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("GFG");
// apply weakCompareAndSetVolatile()
boolean result
= ref.weakCompareAndSetVolatile(
"GFG",
"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#weakCompareAndSetVolatile(V, V)