Java中的 AtomicReferenceArray compareAndSet() 方法及示例
AtomicReferenceArray类的compareAndSet()方法用于原子地将 AtomicReferenceArray 的索引 i 的值设置为 newValue,如果 AtomicReferenceArray 对象的索引 i 处的当前值等于 expectedValue。如果更新成功,此方法将返回 true。
句法:
public final boolean
compareAndSet(
int i, E expectedValue, E newValue)
参数:此方法接受:
- i是执行操作的 AtomicReferenceArray 的索引,
- expectedValue是期望值和
- newValue是要设置的新值。
返回值:该方法成功返回true ,返回false表示实际值不等于预期值。
下面的程序说明了 compareAndSet() 方法:
方案一:
// Java program to demonstrate
// compareAndSet() 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 compareAndSet()
boolean op1
= ref.compareAndSet(0, 5434, 8913);
boolean op2
= ref.compareAndSet(1, 3236, 6543);
// print
System.out.println("Operation at index 0: "
+ op1);
System.out.println("Operation at index 0: "
+ op2);
}
}
输出:
Operation at index 0: false
Operation at index 0: false
方案二:
// Java program to demonstrate
// compareAndSet() 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 compareAndSet()
boolean op1
= ref.compareAndSet(
0, "GFG",
"GEEKS FOR GEEKS");
boolean op2
= ref.compareAndSet(
1, "JS",
"JAVA SCRIPT");
// print
System.out.println("Operation at index 0: "
+ op1);
System.out.println("New value at index 0: "
+ ref.get(0));
System.out.println("Operation at index 1: "
+ op2);
System.out.println("New value at index 1: "
+ ref.get(1));
}
}
输出:
Operation at index 0: true
New value at index 0: GEEKS FOR GEEKS
Operation at index 1: true
New value at index 1: JAVA SCRIPT
参考: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#compareAndSet(int, E, E)