public class TestThreadTerminate {
public static void main(String args[]) throws Exception {
ExecutorService e = Executors.newCachedThreadPool();
Future<Boolean> f = e.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("Step 1!!");
Thread.sleep(5000);
System.out.println("Step 2!!");
Thread.sleep(5000);
System.out.println("Step 3!!");
return true;
}
});
try {
Boolean flag = f.get(1, TimeUnit.SECONDS);
} catch(TimeoutException ex) {
f.cancel(true);
System.out.println("Canceling");
}
System.out.println("FINAL!");
}
}
With this, my output is
Step 1
Canceling
Final
But program terminates a lot later. Why does it happen once thread is interrupted?
If I remove f.cancel(true)
, my thread keeps running and prints following:
Step 1
Canceling
Final
Step 2
Step 3
What can I do to terminate the program i.e to terminate the inner thread? Effectively, I want to use this thread for other tasks in the thread pool which doesn't seem to be happening here.
Putting Thread.currentThread().isInterrupted()
at all the places before returning doesn't look like a good idea.