AtomicReference类的getAndSet()方法用于以原子方式将AtomicReference对象的值设置为newValue,该值作为参数传递并返回AtomicReference对象的旧值,并具有由VarHandle.getAndSet(java.lang.Object ... ).VarHandle.getAndSet(java.lang.Object…)指定将变量作为设置的内存语义,就像将该变量声明为volatile一样。
用法:
public final V getAndSet?(V newValue)
参数:此方法接受newValue作为新值。
返回值:此方法返回AtomicReference的旧值。
以下示例程序旨在说明getAndSet()方法:
程序1:
// Java program to demonstrate
// AtomicReference.getAndSet() method
import java.util.concurrent.atomic.AtomicReference;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReference<Double> ref
= new AtomicReference<Double>();
// set some value
ref.set(1234.00);
// get and replace value
double oldValue
= ref.getAndSet((double)3213);
// print
System.out.println("OLD Value = "
+ oldValue);
System.out.println("NEW Value = "
+ ref.get());
}
}
输出:
OLD Value = 1234.0 NEW Value = 3213.0
程序2:
// Java program to demonstrate
// AtomicReference.getAndSet() method
import java.util.concurrent.atomic.AtomicReference;
public class GFG {
public static void main(String[] args)
{
// create an atomic reference object.
AtomicReference<String> ref
= new AtomicReference<String>();
// set some value
ref.set("AtomicReference old value");
// get and replace value
String oldValue = ref.getAndSet(
"AtomicReference new value");
// print
System.out.println("OLD Value = "
+ oldValue);
System.out.println("NEW Value = "
+ ref.get());
}
}
输出:
OLD Value = AtomicReference old value NEW Value = AtomicReference new value
相关用法
- Java AtomicLong getAndSet()用法及代码示例
- Java AtomicReferenceArray getAndSet()用法及代码示例
- Java AtomicLongArray getAndSet()用法及代码示例
- Java AtomicBoolean getAndSet()用法及代码示例
- Java AtomicInteger getAndSet()用法及代码示例
- Java AtomicIntegerArray getAndSet()用法及代码示例
- Java AtomicReference set()用法及代码示例
- Java AtomicReference get()用法及代码示例
- Java AtomicReference getAndUpdate()用法及代码示例
- Java AtomicReference weakCompareAndSet()用法及代码示例
- Java AtomicReference getAcquire()用法及代码示例
- Java AtomicReference updateAndGet()用法及代码示例
- Java AtomicReference lazySet()用法及代码示例
- Java AtomicReference setRelease()用法及代码示例
- Java AtomicReference compareAndSet()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 AtomicReference getAndSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。