AtomicReferenceArray类的getAndSet()方法用于原子地将AtomicReferenceArray对象的索引i的值设置为newValue,该值作为参数传递并返回AtomicReferenceArray对象的旧值,具有由VarHandle.getAndSet(java.lang .Object…).VarHandle.getAndSet(java.lang.Object…)指定将变量作为设置的内存语义,就像将该变量声明为volatile一样。
用法:
public final E getAndSet(int i, E newValue)
参数:此方法接受:
- i这是执行操作的AtomicReferenceArray的索引,
- newValue 这是要设置的新值。
返回值:此方法返回索引i的旧值。
以下示例程序旨在说明getAndSet()方法:
程序1:
// Java program to demonstrate
// AtomicReferenceArray.getAndSet() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReferenceArray<Integer> ref
= new AtomicReferenceArray<Integer>(3);
// set some value
ref.set(0, 1234);
ref.set(1, 4322);
// apply getAndSet()
int oldV1 = ref.getAndSet(0, 8913);
int oldV2 = ref.getAndSet(1, 6543);
// 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));
}
}
输出:
Old value at index 0:1234 New value at index 0:8913 Old value at index 1:4322 New value at index 1:6543
程序2:
// Java program to demonstrate
// AtomicReferenceArray.getAndSet() method
import java.util.concurrent.atomic.*;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReferenceArray<String> ref
= new AtomicReferenceArray<String>(3);
// set some value
ref.set(0, "GFG");
ref.set(1, "JS");
// apply getAndSet()
String oldV1
= ref.getAndSet(0, "GEEKS FOR GEEKS");
String oldV2
= ref.getAndSet(1, "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));
}
}
输出:
Old value at index 0:GFG New value at index 0:GEEKS FOR GEEKS Old value at index 1:JS New value at index 1:JAVA SCRIPT
相关用法
- Java AtomicIntegerArray getAndSet()用法及代码示例
- Java AtomicLongArray getAndSet()用法及代码示例
- Java AtomicLong getAndSet()用法及代码示例
- Java AtomicInteger getAndSet()用法及代码示例
- Java AtomicBoolean getAndSet()用法及代码示例
- Java AtomicReference getAndSet()用法及代码示例
- Java AtomicReferenceArray set()用法及代码示例
- Java AtomicReferenceArray get()用法及代码示例
- Java AtomicReferenceArray toString()用法及代码示例
- Java AtomicReferenceArray compareAndSet()用法及代码示例
- Java AtomicReferenceArray updateAndGet()用法及代码示例
- Java AtomicReferenceArray length()用法及代码示例
- Java AtomicReferenceArray setPlain()用法及代码示例
- Java AtomicReferenceArray getOpaque()用法及代码示例
- Java AtomicReferenceArray compareAndExchange()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 AtomicReferenceArray getAndSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。