如何中断ExecutorService的线程 [英] How to interrupt ExecutorService's threads

查看:251
本文介绍了如何中断ExecutorService的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 Executors.newSingleThreadExecutor()返回的 ExecutorService 时,如何中断?

When using the ExecutorService returned by Executors.newSingleThreadExecutor(), how do I interrupt it?

推荐答案

为了做到这一点,你需要 submit() code> ExecutorService ,而不是调用 execute()。当执行此操作时,会返回一个 Future ,可用于操作计划任务。特别是,您可以致电 <$ c $在 Future 上关闭 cancel(true) 以中断当前正在执行的任务尚未开始运行)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆