Java中的 AtomicReferenceArray compareAndExchangeAcquire() 方法及示例
AtomicReferenceArray类的compareAndExchangeAcquire()方法用于原子地将 AtomicReferenceArray 的索引 i 的值设置为 newValue,如果被称为见证值的 AtomicReferenceArray 对象的索引 i 处的当前值等于预期值。此方法将返回见证值,这将与预期值相同。此方法使用与 memory_order_acquire 排序兼容的内存排序效果交换值。
句法:
public final boolean
compareAndExchangeAcquire(
int i, E expectedValue, E newValue)
参数:此方法接受:
- i是执行操作的 AtomicReferenceArray 的索引,
- expectedValue是期望值和
- newValue是要设置的新值。
返回值:该方法返回见证值,如果成功则与预期值相同。
下面的程序说明了 compareAndExchangeAcquire() 方法:
方案一:
// Java program to demonstrate
// compareAndExchangeAcquire() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReferenceArray ref
= new AtomicReferenceArray(3);
// set some value
ref.set(0, 1234);
ref.set(1, 4322);
// apply compareAndExchangeAcquire()
int oldV1
= ref.compareAndExchangeAcquire(
0, 1234, 8913);
int oldV2
= ref.compareAndExchangeAcquire(
1, 4322, 6543);
// print
System.out.println(
"Old value at index 0: "
+ oldV1);
System.out.println(
"Old value at index 1: "
+ oldV2);
}
}
输出:
方案二:
// Java program to demonstrate
// compareAndExchangeAcquire() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReferenceArray ref
= new AtomicReferenceArray(3);
// set some value
ref.set(0, "GFG");
ref.set(1, "JS");
// apply compareAndExchangeAcquire()
String oldV1
= ref.compareAndExchangeAcquire(
0, "GFG",
"GEEKS FOR GEEKS");
String oldV2
= ref.compareAndExchangeAcquire(
1, "JS",
"JAVA SCRIPT");
// print
System.out.println(
"Old value at index 0: "
+ oldV1);
System.out.println(
"New value at index 0: "
+ ref.get(0));
System.out.println(
"Old value at index 1: "
+ oldV2);
System.out.println(
"New value at index 1: "
+ ref.get(1));
}
}
输出:
参考资料: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#compareAndExchangeAcquire(int, E, E)