gpt4 book ai didi

java - 如何在 CompletableFuture.supplyAsync(Supplier supplier) 方法中使用所需数量的工作线程设置 ForkJoinPool?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:40 28 4
gpt4 key购买 nike

根据甲骨文,

static CompletableFuture supplyAsync(Supplier supplier)Returns a new CompletableFuture that is asynchronously completed by atask running in the ForkJoinPool.commonPool() with the value obtainedby calling the given Supplier.

static CompletableFuture supplyAsync(Supplier supplier, Executorexecutor) Returns a new CompletableFuture that is asynchronouslycompleted by a task running in the given executor with the valueobtained by calling the given Supplier.

如果我使用"static CompletableFuture supplyAsync(Supplier supplier)" 方法,它默认使用ForkJoinPool.commonPool()。这将返回一个 ForkJoinPool,其工作线程数等于正在运行的机器中的可用内核数。

但是,我想使用 ForkJoinPool 和我自定义的工作线程数。使用 ForkJoinPool.commonPool() 我无法做到这一点。

那么我如何使用 CompletableFuture.supplyAsync 方法和我声明的 ForkJoinPool 使用我想要的工作线程数?

最佳答案

ForkJoinPool实现 Executor

因此,您可以这样编写代码:

int threadCount = 3;
ForkJoinPool myPool = new ForkJoinPool(threadCount);
CompletableFuture cf = CompletableFuture.supplyAsync(mySup, myPool);

关于java - 如何在 CompletableFuture.supplyAsync(Supplier<U> supplier) 方法中使用所需数量的工作线程设置 ForkJoinPool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36569775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com