Java ExecutorService什么时候调用shutdown()

我是
Java多线程的新手.我正在使用ExecutorService下载一堆网页进行分析.目前我的方法是提交所有Callables并将Future对象放在循环列表中,然后调用shutdown()和awaitTermination(),最后我处理将来的列表.

我的问题是在我的情况下,在填写这样的未来列表之后放置shutdown()是否可以?由于Future的get()已经阻塞,直到任务完成,似乎我应该在完成处理所有未来时调用它. 最佳答案 注意shutdown()的javadoc

Initiates an orderly shutdown in which previously submitted tasks are
executed, but no new tasks will be accepted. Invocation has no
additional effect if already shut down.

这是一个干净的停止.提交的任务将一直运行,直到完成.既然你也有awaitTermination()

Blocks until all tasks have completed execution after a shutdown
request, or the timeout occurs, or the current thread is interrupted,
whichever happens first.

你的未来#get()方法调用将立即返回(如果awaitTermination()没有超时).你正在做的事情没有问题.

确保您的任务不会永远运行.

点赞