Java中的 AtomicReferenceArray compareAndExchange() 方法及示例
AtomicReferenceArray类的compareAndExchange()方法用于将 AtomicReferenceArray 的索引 i 的值自动设置为 newValue,如果被称为见证值的 AtomicReferenceArray 对象的索引 i 处的当前值等于预期值。此方法将返回见证值,该值与预期值相同。此方法处理具有读取的内存语义的操作,就好像变量被声明为易失性一样。
句法:
public final boolean
compareAndExchange(
int i, E expectedValue, E newValue)
参数:此方法接受:
- i是执行操作的 AtomicReferenceArray 的索引,
- expectedValue是期望值和
- newValue是要设置的新值。
返回值:该方法返回见证值,如果成功则与预期值相同。
下面的程序说明了 compareAndExchange() 方法:
方案一:
// Java program to demonstrate
// compareAndExchange() 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 compareAndExchange()
int oldV1
= ref.compareAndExchange(0, 1234, 8913);
int oldV2
= ref.compareAndExchange(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
// compareAndExchange() 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 compareAndExchange()
String oldV1
= ref.compareAndExchange(
0, "GFG",
"GEEKS FOR GEEKS");
String oldV2
= ref.compareAndExchange(
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#compareAndExchange(int, E, E)