如何在 CompletableFuture.supplyAsync(Supplier<U> supplier) 方法中使用所需数量的工作线程设置 ForkJoinPool?
How to set ForkJoinPool with the desired number of worker threads in CompletableFuture.supplyAsync(Supplier<U> supplier) method?
根据 Oracle,
static CompletableFuture supplyAsync(Supplier supplier)
Returns a new CompletableFuture that is asynchronously completed by a
task running in the ForkJoinPool.commonPool() with the value obtained
by calling the given Supplier.
static CompletableFuture supplyAsync(Supplier supplier, Executor
executor) Returns a new CompletableFuture that is asynchronously
completed by a task running in the given executor with the value
obtained by calling the given Supplier.
如果我使用 "static CompletableFuture supplyAsync(Supplier supplier)" 方法,它默认使用 ForkJoinPool.commonPool() . returns 一个 ForkJoinPool,其工作线程数等于 运行 机器中的可用内核数。
但是,我想使用 ForkJoinPool 和我自定义的工作线程数。使用 ForkJoinPool.commonPool() 我做不到。
那么我如何使用 CompletableFuture.supplyAsync 方法和我声明的 ForkJoinPool 使用我想要的工作线程数?
ForkJoinPool
实施 Executor
.
因此,您可以这样编写代码:
int threadCount = 3;
ForkJoinPool myPool = new ForkJoinPool(threadCount);
CompletableFuture cf = CompletableFuture.supplyAsync(mySup, myPool);
根据 Oracle,
static CompletableFuture supplyAsync(Supplier supplier) Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.
static CompletableFuture supplyAsync(Supplier supplier, Executor executor) Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier.
如果我使用 "static CompletableFuture supplyAsync(Supplier supplier)" 方法,它默认使用 ForkJoinPool.commonPool() . returns 一个 ForkJoinPool,其工作线程数等于 运行 机器中的可用内核数。
但是,我想使用 ForkJoinPool 和我自定义的工作线程数。使用 ForkJoinPool.commonPool() 我做不到。
那么我如何使用 CompletableFuture.supplyAsync 方法和我声明的 ForkJoinPool 使用我想要的工作线程数?
ForkJoinPool
实施 Executor
.
因此,您可以这样编写代码:
int threadCount = 3;
ForkJoinPool myPool = new ForkJoinPool(threadCount);
CompletableFuture cf = CompletableFuture.supplyAsync(mySup, myPool);