首页 > 解决方案 > ExecutorService - shutdown() 是否会中断已经执行的任务?

问题描述

为避免等待时间过长,建议您在调用shutdown()之前调用 a awaitTermination(),因为后者不是为了杀死 executor。但是,对于等待任务完成,您是否应该使用invokeAll()来代替等待执行程序 关闭

javadoc表明,如果你想引起中断,应该这样做shutDownNow()。那么shutdown()实际上是否会中断已经执行的任务,因为它是否优雅有序?

谢谢!

标签: java

解决方案


关机文件说:

    /** 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,但接收一个任务集合。

两种方法的这些文档注释应该清楚地使您了解差异。


推荐阅读