问题
Suppose I have a Runnable
instance:
class MyTask implements Runnable {
public void run() {
//some heavy calculation which takes time
Thread.sleep(5000)
//rest code
...
}
}
Then, I use ExecutorService to submit the above task:
ExecutorService service = Executors.newFixedThreadPool(3);
Future<?> task = service.submit(new MyTask());
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.
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.
回答1:
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.
See http://www.ibm.com/developerworks/library/j-jtp05236/
回答2:
There is a method called isInterrupted(), this tells the running code in the thread that it is interrupted by returning a true/false.
This is usually checked by the methods like wait, sleep which you might invoke in the thread. If however you do not use these methods, then you will have to manually check this method [ isInterrupted() ] to determine whether someone has interrupted your thread.
If by any chance you get a true, you can decide what action to perform (let us say for example: throw a InterruptedException or break from a loop, etc...)
来源:https://stackoverflow.com/questions/26516372/what-is-happening-underneath-the-future-canceltrue