如何限制 ParallelStream 中的并行执行数?

How to limit number of parallel executions in ParallelStream?

list.parallelStream().forEach(element -> ...);

现在如何限制并行线程的数量?

过去有一个“hack”来设置系统 属性 java.util.concurrent.ForkJoinPool.common.parallelism。但这感觉不对,而且它不再起作用了。

您能否建议如何将列表分块 分成 4 个部分,然后仅 运行 这 4 个部分并行?

我认为您更愿意限制正在执行的并发任务的数量,因此我认为这里没有必要使用并行流,只要 Java 中有一个简单的解决方案即可并发包。请改用 ExecutorService 和固定的四线程池。

Collection<Callable<Void>> = ...
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.invokeAll(callables);

如果你真的想在并行流中使用自定义线程池,请参考这个问题:Custom thread pool in Java 8 parallel stream

使用自定义线程池。

在此处阅读更多内容: https://www.baeldung.com/java-8-parallel-streams-custom-threadpool

这里: https://www.baeldung.com/java-when-to-use-parallel-stream

您必须使用具有所需线程数的自定义 ForkJoinPool 才能并行执行您的任务。

ForkJoinPool customThreadPool = new ForkJoinPool(NB_THREADS);
customThreadPool.submit(
() -> list.parallelStream().forEach(element -> ...);