AtomicReference類的getAndUpdate()方法用於原子更新,該更新通過對當前值應用指定的updateFunction操作來更新AtomicReference的當前值。它以updateFunction接口的對象為參數,並將該對象中指定的操作應用於當前值。它返回先前的值。
用法:
public final V getAndUpdate(UnaryOperator<V> updateFunction)
參數:此方法接受updateFunction,它是沒有副作用的函數。
返回值:此方法返回prevoius值。
以下示例程序旨在說明getAndUpdate()方法:
程序1:
// Java program to demonstrate
// AtomicReference.getAndUpdate() method
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
// AtomicReference with value
AtomicReference<Integer> ref
= new AtomicReference<>(987654);
// Declaring the updateFunction
// applying function
UnaryOperator twoDigits
= (v)
-> v.toString()
.substring(0, 2);
// apply getAndUpdate()
int value = ref.getAndUpdate(twoDigits);
// print AtomicReference
System.out.println(
"The AtomicReference previous value:"
+ value);
System.out.println(
"The AtomicReference new value:"
+ ref.get());
}
}
輸出:
程序2:
// Java program to demonstrate
// AtomicReference.getAndUpdate() method
import java.util.concurrent.atomic.*;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
// AtomicReference with value
AtomicReference<String> ref
= new AtomicReference<>("welcome");
// Declaring the updateFunction
// applying function
UnaryOperator twoDigits
= (v) -> v + " to gfg";
// apply getAndUpdate()
String value
= ref.getAndUpdate(twoDigits);
// print AtomicReference
System.out.println(
"The AtomicReference previous value:"
+ value);
System.out.println(
"The AtomicReference new value:"
+ ref.get());
}
}
輸出:
相關用法
- Java AtomicLong getAndUpdate()用法及代碼示例
- Java AtomicReferenceArray getAndUpdate()用法及代碼示例
- Java AtomicIntegerArray getAndUpdate()用法及代碼示例
- Java AtomicLongArray getAndUpdate()用法及代碼示例
- Java AtomicReference set()用法及代碼示例
- Java AtomicReference get()用法及代碼示例
- Java AtomicReference setRelease()用法及代碼示例
- Java AtomicReference compareAndExchange()用法及代碼示例
- Java AtomicReference setOpaque()用法及代碼示例
- Java AtomicReference compareAndExchangeRelease()用法及代碼示例
- Java AtomicReference accumulateAndGet()用法及代碼示例
- Java AtomicReference getPlain()用法及代碼示例
- Java AtomicReference getOpaque()用法及代碼示例
- Java AtomicReference getAndAccumulate()用法及代碼示例
- Java AtomicReference compareAndSet()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 AtomicReference getAndUpdate() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。