如何使用 CompletableFuture 打开列表中的所有结果并将其收集到线程中?
How to open and gather all the results from a list into threads with CompletableFuture?
我有一个字符串列表,对于每个字符串,我需要打开一个新线程并将所有信息收集到一个 CompletableFuture 中。
这是我的迭代:
for (String result: results) {
candidateInfos.add(getCandidatesInfo(result));
}
我是第一次尝试线程的实现,希望能得到一些帮助。
您可以为每个方法调用构建 Stream,然后可以将结果收集到列表中,如下所示。
Stream.Builder<Supplier<CanditateInfo>> streamBuilder = Stream.builder();
results.forEach(string-> streamBuilder.accept(() -> this.getCandidatesInfo(string)));
List<CanditateInfo> candidateInfos = streamBuilder.build().map(supplier -> CompletableFuture.supplyAsync(supplier, Executors.newFixedThreadPool(
results.size()))).collect(Collectors.toList()).stream().map(
CompletableFuture::join).collect(Collectors.toList());
这里我使用了单独的 Executor,因为默认情况下,java 使用公共的 Fork 和 Join Pool,如果池已满,它将阻塞所有其他线程。有关详细信息,请参阅 http://fahdshariff.blogspot.in/2016/06/java-8-completablefuture-vs-parallel.html
编辑:减少语法。
您可以使用列表直接创建流,或者如果您使用数组,则使用 Arrays.stream 而不是使用 Stream.Builder
List<CanditateInfo> candidateInfos = results.stream().map(s ->
CompletableFuture.supplyAsync(this.getCandidatesInfo(s), Executors.newFixedThreadPool(
results.size()))).map(CompletableFuture::join).collect(Collectors.toList());
我有一个字符串列表,对于每个字符串,我需要打开一个新线程并将所有信息收集到一个 CompletableFuture 中。
这是我的迭代:
for (String result: results) {
candidateInfos.add(getCandidatesInfo(result));
}
我是第一次尝试线程的实现,希望能得到一些帮助。
您可以为每个方法调用构建 Stream,然后可以将结果收集到列表中,如下所示。
Stream.Builder<Supplier<CanditateInfo>> streamBuilder = Stream.builder();
results.forEach(string-> streamBuilder.accept(() -> this.getCandidatesInfo(string)));
List<CanditateInfo> candidateInfos = streamBuilder.build().map(supplier -> CompletableFuture.supplyAsync(supplier, Executors.newFixedThreadPool(
results.size()))).collect(Collectors.toList()).stream().map(
CompletableFuture::join).collect(Collectors.toList());
这里我使用了单独的 Executor,因为默认情况下,java 使用公共的 Fork 和 Join Pool,如果池已满,它将阻塞所有其他线程。有关详细信息,请参阅 http://fahdshariff.blogspot.in/2016/06/java-8-completablefuture-vs-parallel.html
编辑:减少语法。
您可以使用列表直接创建流,或者如果您使用数组,则使用 Arrays.stream 而不是使用 Stream.Builder
List<CanditateInfo> candidateInfos = results.stream().map(s ->
CompletableFuture.supplyAsync(this.getCandidatesInfo(s), Executors.newFixedThreadPool(
results.size()))).map(CompletableFuture::join).collect(Collectors.toList());