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.