gpt4 book ai didi

java - 速率限制执行器中的线程数(Java)

转载 作者:行者123 更新时间:2023-11-30 06:55:31 24 4
gpt4 key购买 nike

如何限制 Executor 中执行的线程数?例如,在下面的代码中:

            executor = Executors.newFixedThreadPool(this.noOfThreads);
for (int i = 0; i < sections.size(); i++) {
DomNode section = sections.get(i);
// Retrieve the url of the subsection
String subsectionUrl = section.getNodeValue();

if(i != 0 && (i % noOfThreadsPerSection == 0)) {
// Add section threads to the executor
executor.execute(new BrowseSection(filter, webClient, subsectionUrl));
} else {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
// We should normally never get here
}
}
}

executor.execute() 被调用时,如果线程池中充满了正在运行的线程会怎样?

上面的代码并没有检查执行器中线程是否还在运行,而是检查已经启动的线程数。

最佳答案

无论是否有任何事情要做,池都会创建固定数量的线程。它不会根据您的使用方式而改变。

您的作业被传递到一个队列,线程池从队列中获取任务。当池不全忙时,任务几乎在添加后立即从队列中拉出。当您有更多任务时,队列会变长。

在 Java 8 中,它避免为每个项目创建任务,而是将工作分解为多个部分。这种方式比以简单的方式使用 ExecutorService 更有效。

在 Java 8 中你会写。

sections.parallelStream()
.map(s -> s.getNodeValue())
.forEach(s -> new BrowseSection(filter, webClient, s).run());

无需启动线程池并再次关闭它等。这会等待所有任务完成。

您可以更改 ForkJoinPool.commonPool() 的大小通过命令行设置

-Djava.util.concurrent.ForkJoinPool.common.parallelism=N

如果您在此类加载之前进行设置,您也可以实用地设置它。

关于java - 速率限制执行器中的线程数(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256064/

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