**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。
上个月关门了。
改进这个问题
我在哪里有问题 CompletableFuture
循环中的任务不是并行运行,而是同步运行:
List<List<File>> filesLists = divideArrayIntoChunks(Arrays.asList(filesArray), 10);
// number of tasks
int numberOfTasks = filesLists.size();
List<CompletableFuture<TreeMap<String, HashMap<String, Integer>>>> builderPartsMapFutures = Lists
.newArrayList();
for (int i = 0; i < numberOfTasks; i++) {
List<File> filesList = filesLists.get(i);
builderPartsMapFutures.add(getCompetableFutureResult(filesList, fileNameAndCharactersAmountMatchersMap,
namesElementsMap, namesAndFileNamesMatchingCharactersMap));
}
@SuppressWarnings("rawtypes")
CompletableFuture[] futureResultArray = builderPartsMapFutures
.toArray(new CompletableFuture[builderPartsMapFutures.size()]);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray);
combinedFuture.get();
CompletableFuture<List<TreeMap<String, HashMap<String, Integer>>>> finalResults = combinedFuture.thenApply(
voidd -> builderPartsMapFutures.stream().map(future -> future.join()).collect(Collectors.toList()));
finalResults.thenAccept(result -> System.out.println(result));
这是 getCompetableFutureResult()
方法:
public static CompletableFuture<TreeMap<String, HashMap<String, Integer>>> getCompetableFutureResult(
List<File> filesList, HashMap<String, Integer> fileNameAndCharactersAmountMatchersMap,
TreeMap<String, ArrayList<String>> namesElementsMap,
TreeMap<String, Map<String, Integer>> namesAndFileNamesMatchingCharactersMap) {
return CompletableFuture
.supplyAsync(() -> buildNamesAndFileNamesWithMatchingCharactersMapForEachChunk(filesList,
fileNameAndCharactersAmountMatchersMap, namesElementsMap,
namesAndFileNamesMatchingCharactersMap));
}
1条答案
按热度按时间b1uwtaje1#
返回一个新的completablefuture,该Future由运行在forkjoinpool.commonpool()中的任务异步完成,其值通过调用给定的供应商获得。
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/completablefuture.html#supplyasync-java.util.function.supplier供应商-
下面是代码中相同工作流的简化版本。
输出显示线程正在异步运行。它不是一个接一个的。