Java中的 AtomicReference weakCompareAndSetAcquire() 方法及示例
AtomicReference类的weakCompareAndSetAcquire()方法用于将 AtomicReference 的值自动设置为 newValue,如果当前值等于作为参数传递的 expectedValue。此方法使用与 memory_order_acquire 排序兼容的内存排序效果更新值。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。
句法:
public final boolean
weakCompareAndSetAcquire(V expectedValue,
V newValue)
参数:此方法接受期望值和newValue ,这是要设置的新值。
返回值:如果成功,此方法返回true。
下面的程序说明了weakCompareAndSetAcquire() 方法:
方案一:
Java
// Java program to demonstrate
// AtomicReference.weakCompareAndSetAcquire() 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(11111111L);
// apply weakCompareAndSetAcquire()
boolean result
= ref.weakCompareAndSetAcquire(
1111111111111L,
999999L);
// print value
System.out.println("Setting new value"
+ " is successful = "
+ result);
System.out.println("Value = " + ref.get());
}
}
Java
// Java program to demonstrate
// AtomicReference.weakCompareAndSetAcquire() 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 weakCompareAndSetAcquire()
boolean result
= ref.weakCompareAndSetAcquire(
"WELCOME TO GEEKS FOR GEEKS",
"WELCOLME GEEKS");
// print value
System.out.println("Setting new value"
+ " is successful = "
+ result);
System.out.println("Value = " + ref.get());
}
}
输出:
方案二:
Java
// Java program to demonstrate
// AtomicReference.weakCompareAndSetAcquire() 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 weakCompareAndSetAcquire()
boolean result
= ref.weakCompareAndSetAcquire(
"WELCOME TO GEEKS FOR GEEKS",
"WELCOLME 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#weakCompareAndSetAcquire(V, V)