有没有办法告诉ExecutorService
在固定的线程池场景中关闭空闲线程?
问候!
::编辑: 好的,我很沮丧。我现在切换到ThreadPoolExecutor,它允许我使用以下构造函数指定keepAliveTime:
private final LinkedBlockingQueue<Runnable> threadPool = new LinkedBlockingQueue<Runnable>()
public Crawler(String startingUrl, int numThreads, int depth) {
System.setProperty("http.agent", "");
// System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "info");
this.url = startingUrl;
this.maxDepth = depth;
executorService = new ThreadPoolExecutor(
numThreads,
numThreads,
2000,
TimeUnit.MILLISECONDS,
threadPool,
new ThreadPoolExecutor.CallerRunsPolicy());
databaseHandler = new DatabaseHandler();
try {
databaseHandler.init();
} catch (final SQLException e) {
e.printStackTrace();
}
}
// this method is invoked by each Runnable when it found new links
@Override
public void queueLink(String link, int currentDepth) throws Exception {
if (currentDepth < maxDepth) {
final LinkFinder lf = new LinkFinder(link, currentDepth, this);
executorService.execute(lf);
} else {
System.out.println("max depth reached!");
System.out.println("num queued tasks: " + threadPool.size());
}
}
每个新的Runnable都会收到当前的深度属性。在每个Runnable currentDepth的最后一行上升1.当然“达到最大深度”按预期打印出来,以及“num queued tasks:0”。然而,线程继续运行数小时。
我的印象是params keepAliveTime和TimeUnit.MILLISECONDS会确保在闲置两秒后线程被关闭(假设没有其他任务排队)。
我错过了什么?我的意思是,我可以计算我点击else语句然后手动关闭执行程序的次数,但由于ThreadPoolExecutor已经提供了基于时间的行为,我宁愿坚持这一点。
现在我认为这与我设定的政策有关......要考虑一下。不管怎样,谢谢
问候!
答案 0 :(得分:0)
setKeepAliveTime(long time, TimeUnit unit)
或强>
您可以通过setCorePoolSize(int corePoolSize)