如何在CompletableFuture.supplyAsync(Supplier <U>供应商)方法中使用所需数量的工作线程设置ForkJoinPool?

Md.*_*ail 6 java multithreading forkjoinpool completable-future

根据Oracle,

static CompletableFuture supplyAsync(供应商供应商) 返回一个新的CompletableFuture,它由在ForkJoinPool.commonPool()中运行的任务异步完成,其中包含通过调用给定供应商获得的值.

static CompletableFuture supplyAsync(供应商供应商,执行程序执行程序)返回由给定执行程序中运行的任务异步完成的新CompletableFuture,其中包含通过调用给定供应商获得的值.

如果我使用"静态CompletableFuture supplyAsync(供应商供应商)"方法,它默认使用ForkJoinPool.commonPool().这将返回一个ForkJoinPool,其工作线程数等于正在运行的计算机中的可用核心数.

但是,我想使用ForkJoinPool和我自定义的工作线程数.使用ForkJoinPool.commonPool()我不能这样做.

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

flo*_*flo 7

ForkJoinPool实施Executor.

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

int threadCount = 3;
ForkJoinPool myPool = new ForkJoinPool(threadCount);
CompletableFuture cf = CompletableFuture.supplyAsync(mySup, myPool);
Run Code Online (Sandbox Code Playgroud)