如何中断 ExecutorService 的线程
当使用Executors.newSingleThreadExecutor()
返回的ExecutorService
时,如何中断它?
When using the ExecutorService
returned by Executors.newSingleThreadExecutor()
, how do I interrupt it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您需要
submit()
将任务发送给ExecutorService
,而不是调用execute()
。当您执行此操作时,将返回一个可用于操作计划任务的Future
。特别是,您可以调用cancel(true)
在关联的Future
上中断当前正在执行的任务(或者如果任务尚未开始运行则完全跳过执行) 。顺便说一下,
Executors.newSingleThreadExecutor()
实际上是一个ExecutorService
。In order to do this, you need to
submit()
a task to anExecutorService
, rather than callingexecute()
. When you do this, aFuture
is returned that can be used to manipulate the scheduled task. In particular, you can callcancel(true)
on the associatedFuture
to interrupt a task that is currently executing (or skip execution altogether if the task hasn't started running yet).By the way, the object returned by
Executors.newSingleThreadExecutor()
is actually anExecutorService
.中断执行程序的内部管理线程的另一种方法是调用
ExecutorService
上的shutdownNow(..)
方法。但请注意,与 @erickson 的解决方案相反,这将导致整个 ThreadPoolExecutor 变得不适合进一步使用。我发现这种方法在不再需要
ExecutorService
的情况下特别有用,并且不需要继续关注Future
实例(一个典型的例子是exit(..)
应用程序的方法)。来自
ExecutorService#shutdownNow(..)
javadocs 的相关信息:Another way to interrupt the executor's internally managed thread(s) is to call the
shutdownNow(..)
method on yourExecutorService
. Note, however, that as opposed to @erickson's solution, this will result in the wholeThreadPoolExecutor
becoming unfit for further use.I find this approach particularly useful in cases where the
ExecutorService
is no longer needed and keeping tabs on theFuture
instances is otherwise unnecessary (a prime example of this being theexit(..)
method of your application).Relevant information from the
ExecutorService#shutdownNow(..)
javadocs:一种正确的方法可能是为
ExecutorService
自定义/注入 ThreadFactory ,并从线程工厂中获取创建的线程的句柄,然后您可以安排一些任务来执行中断感兴趣的线程。ThreadFactory
中覆盖方法newThread
的演示代码部分:然后您可以使用下面的代码来构造您的
ExecutorService
实例:然后 5 秒后,中断信号将被发送到ExecutorService中的线程。
One proper way could be customizing/injecting the
ThreadFactory
for theExecutorService
and from within the thread factory, you got the handle of the thread created, then you can schedule some task to interrupt the thread being interested.Demo code part for the overwrited method
newThread
inThreadFactory
:Then you can use below code to construct your
ExecutorService
instance:Then after 5 seconds, an interrupt signal will be sent to the threads in
ExecutorService
.