java - ExecutorService - shutdown() 是否会中断已经执行的任务?
问题描述
为避免等待时间过长,建议您在调用shutdown()
之前调用 a awaitTermination()
,因为后者不是为了杀死 executor。但是,对于等待任务完成,您是否应该使用invokeAll()
来代替等待执行程序 关闭?
javadoc表明,如果你想引起中断,应该这样做shutDownNow()
。那么shutdown()
实际上是否会中断已经执行的任务,因为它是否优雅有序?
谢谢!
解决方案
关机文件说:
/** 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.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
shutdownNow 文档说:
/**
* Attempts to stop all actively executing tasks, halts the
* processing of waiting tasks, and returns a list of the tasks
* that were awaiting execution.
*
* <p>This method does not wait for actively executing tasks to
* terminate. Use {@link #awaitTermination awaitTermination} to
* do that.
*
* <p>There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. For example, typical
* implementations will cancel via {@link Thread#interrupt}, so any
* task that fails to respond to interrupts may never terminate.
*
调用所有文档说:
/**
* Executes the given tasks, returning a list of Futures holding
* their status and results when all complete.
* {@link Future#isDone} is {@code true} for each
* element of the returned list.
* Note that a <em>completed</em> task could have
* terminated either normally or by throwing an exception.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*/
invokeAll 类似于 execute,但接收一个任务集合。
两种方法的这些文档注释应该清楚地使您了解差异。
推荐阅读
- javascript - Flex box 两列换行
- vba - 到 SQL Server Express 2017 的 VBA 连接字符串
- c++ - C++ 模板专业化在某些情况下无法解决
- apache-spark - Apache Spark 2.3.1 - pyspark.sql.SparkSession.builder.enableHiveSupport() 是否必要?
- javascript - 引导选项卡菜单切换不更改变量
- razor-pages - ASP Core Razor Pages 两种方式绑定
- c# - 带有 RazorEngine 的 Linq 命名空间
- ruby-on-rails - Rails 5.1.4:在插入数据库或仅登录应用程序后,区域设置被重复的路径条目替换
- stata - 使用 Mata xl() 合并 Excel 中的单元格
- powershell - 跨列将变量写入现有 CSV