[英]filtering Future API
我可以過濾異步調用嗎? 未來是否提供一些過濾器,我可以在其中添加條件以等待第一次通話完成而不是放置時間。
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class FactorialCalculator implements Callable<BigInteger> {
private int value;
public FactorialCalculator(int value) {
this.value = value;
}
@Override
public BigInteger call() throws Exception {
var result = BigInteger.valueOf(1);
if (value == 0 || value == 1) {
result = BigInteger.valueOf(1);
} else {
for (int i = 2; i <= value; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
}
TimeUnit.MILLISECONDS.sleep(500);
return result;
}
}
future 的 get() 方法等待結果完成,然后檢索其結果。
ExecResult execResult = getingWsdl.get();
或者您可以使用重載方法 get(long timeout, TimeUnit unit) 最多等待給定時間以完成執行,然后檢索其結果(如果可用)
ExecResult execResult = getingWsdl.get(10, TimeUnit.SECONDS);
或者您也可以將 execResult 放入 Thread 並等待 run() 方法中的條件來評估 execResult。 請注意,如果您想從 Thread 中返回,您可以使用 Callable 接口和 ExecutorService 而不是 Runnable 和 Thread。
查看CompletableFuture
class ,尤其是它實現的CompletionStage
接口。 這允許您按照您的意願將異步操作鏈接在一起。
可能是這樣的:
CompletableFuture<Result> getBoth = CompletableFuture
.completeAsync(getBase,executor)
.thenApplyAsync(getTar,executor);
這將運行getBase
Supplier 以獲取基礎 WSDL,然后如果正常完成,則運行 Function<WSDL,Result> 以獲取第二個數據並將其與第一個數據結合以創建結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.