问题描述
假设我有一个 Runnable
实例:
class MyTask implements Runnable {
public void run() {
//some heavy calculation which takes time
Thread.sleep(5000)
//rest code
...
}
}
然后,我使用ExecutorService提交上述任务:
Then, I use ExecutorService to submit the above task:
ExecutorService service = Executors.newFixedThreadPool(3);
Future<?> task = service.submit(new MyTask());
现在,我可以通过 task.cancel(true)取消任务;
。我所理解的是 task.cancel(true)
将中断运行此任务的工作线程,如 Thread.currentThread() .interrupt()
。但是这个只设置一个标志来告诉工作线程被中断。
Now, I can cancel the task by task.cancel(true);
. What I have understood is that the task.cancel(true)
will interrupt the working thread in which this task is running, like Thread.currentThread().interrupt()
. But this only sets a flag to tell that the working thread is interrupted.
我的问题是:如果 MyTask
Runnable已经开始运行,实际上未来是怎样的。取消(true)
在中停止我的代码运行()
继续执行其余代码?是否有定期检查下方工作线程的中断标志?我的意思是我不明白如何只通过将interrupt标志设置为true来取消run()中的代码。
My question is: if MyTask
Runnable has started running, how actually does future.cancel(true)
stops my code in run()
continuing executing the rest code? Is there a periodical checking for the working thread's interrupted flag underneath? I mean I don't understand how the code in run() can be canceled by only set the interrupted flag to true.
推荐答案
Future.cancel不保证您的工作代码将停止执行。它的作用是设置中断标志并导致任何阻塞JDK调用抛出InterruptedException。您的工作者代码可以选择重新抛出中断的异常并定期检查中断的标志,在这种情况下取消机制将起作用。否则,您可以选择吞下InterruptedException并忽略iterrupted标志,在这种情况下,取消机制除了将cancel标志设置为true之外什么都不做。
Future.cancel does not guarantee that your worker code will stop executing. What it does is set the interrupted flag and cause any blocking JDK calls to throw an InterruptedException. Your worker code may choose to rethrow the interrupted exception and periodically check the interrupted flag, in which case the cancel mechanism will work. Otherwise you may choose to swallow InterruptedException and disregard the iterrupted flag, in which case the cancel mechanism will do nothing but set the cancelled flag to true.
请参阅
这篇关于Future.cancel(true)下面发生了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!