如何限制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/