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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。