Java中的 AtomicReference compareAndExchange() 方法及示例
AtomicReference类的compareAndExchange()方法用于原子地将值设置为 newValue 到 AtomicReference 对象,如果被称为见证值的 AtomicReference 对象的当前值等于预期值。该方法将返回见证值,这将与预期值相同。此方法处理具有读取的内存语义的操作,就好像变量被声明为易失性一样。
句法:
public final V compareAndExchange(V expectedValue,
V newValue)
参数:此方法接受期望值和newValue ,这是要设置的新值。
返回值:该方法返回见证值,如果成功则与预期值相同。
下面的程序说明了 compareAndExchange() 方法:
方案一:
// Java program to demonstrate
// AtomicReference.compareAndExchange() 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(999);
// apply compareAndExchange()
Integer oldValue
= ref.compareAndExchange(
999,
999999);
// print value
System.out.println("Witness Value= "
+ oldValue);
}
}
输出:
方案二:
// Java program to demonstrate
// AtomicReference.compareAndExchange() 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("GFG");
// apply compareAndExchange()
String oldValue
= ref.compareAndExchange(
"GFG",
"Geeks for Geeks");
// print value
System.out.println("Witness Value= "
+ oldValue);
}
}
输出:
参考: https: Java/util/concurrent/atomic/AtomicReference.html#compareAndExchange(V, V)