如何中断ExecutorService的线程 [英] How to interrupt ExecutorService's threads
问题描述
当使用 Executors.newSingleThreadExecutor()
返回的 ExecutorService
时,如何中断?
When using the ExecutorService
returned by Executors.newSingleThreadExecutor()
, how do I interrupt it?
推荐答案
为了做到这一点,你需要 submit()
code> ExecutorService ,而不是调用 execute()
。当执行此操作时,会返回一个 Future
,可用于操作计划任务。特别是,您可以致电 <$ c $在 Future
上关闭
In order to do this, you need to submit()
a task to an ExecutorService
, rather than calling execute()
. When you do this, a Future
is returned that can be used to manipulate the scheduled task. In particular, you can call cancel(true)
on the associated Future
to interrupt a task that is currently executing (or skip execution altogether if the task hasn't started running yet).
顺便说一下, Executors.newSingleThreadExecutor()
实际上是 ExecutorService
。
这篇关于如何中断ExecutorService的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!