如何限制在Executor
中执行的线程数?例如,在代码波纹管:速率限制执行程序(Java)中的线程数
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()
被调用时,如果线程池充满运行的线程会发生什么?
上面的代码不检查线程是否仍在执行程序中运行,而是线程数量已经启动。
,数量线程受限于this.noOfThreads。它永远不会比这更大 –
noOfThreads是在给定时间运行的一批线程的大小(假设有更多部分)。但是,如果节的数量大于this.noOfThreads,并且线程仍未完成,那么执行if时会发生什么情况?执行程序是否等待某些线程完成或不完成? – Sebi
您可以阅读更多关于ThreadPoolExecutor的信息:https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html –