问题是我必须一一调用API,所以我使用CompleableFunction,如下
List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
List<Bclass> listAll = new ArrayList<>();
for (SthClass e : result) {
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> fundInService.doRetryTransaction(retryTransactionRequestDto), threadConfiguration.getAsyncExecutor())
.thenAccept((result) -> {
Aclass a = new Aclass();
listAll.add(a);
});
completableFutures.add(future);
}
CompletableFuture<Void> allFutures = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]));
allFutures.get();
我从 allFutures 获得了随机大小的 listAll
我不知道这段代码发生了什么,Java 新手
使用
synchronizedList
代替ArrayList
,因为ArrayList
不是线程安全的
List<Bclass> listAll = Collections.synchronizedList( new ArrayList() );
上面 divilipir 的回答对我有用!非常感谢!