Attempts to stop all actively executing tasks, halts the processing of
waiting tasks, and returns a list of the tasks that were awaiting
execution.
There are no guarantees beyond best-effort attempts to stop processing
actively executing tasks. For example, typical implementations will
cancel via Thread.interrupt, so any task that fails to respond to
interrupts may never terminate.
# 1 楼答案
为了做到这一点,您需要将^{} 任务} 来中断当前正在执行的任务(如果任务尚未开始运行,则完全跳过执行)
ExecutorService
,而不是调用execute()
。执行此操作时,将返回一个Future
,可用于操作计划任务。特别是,您可以在关联的Future
上调用^{顺便说一下,^{} 返回的对象实际上是一个
ExecutorService
# 2 楼答案
一种合适的方法是为executorservice定制/注入ThreadFactory,在线程工厂中,创建线程的句柄,然后安排一些任务来中断感兴趣的线程
ThreadFactory中被覆盖的方法“newThread”的演示代码部分:
然后,您可以使用以下内容构建executorservice实例:
然后在5秒后,一个中断信号将发送到executorservice中的线程
# 3 楼答案
中断执行器的内部管理线程的另一种方法是在
ExecutorService
上调用shutdownNow(..)
方法。但是,请注意,与@erickson的解决方案相反,这将导致整个ThreadPoolExecutor
变得不适合进一步使用我发现这种方法在不再需要
ExecutorService
的情况下特别有用,并且不需要对Future
实例进行监视(应用程序的exit(..)
方法就是一个很好的例子)来自Java文档的相关信息: