From java docs on Future.cancel()
boolean cancel(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task. This
If it is not interrupting it will simply tell the future that is is cancelled. You can check that via isCancelled() but nothing happens if you don't check that manually.
Below example code shows how you could do it.
private static FutureTask task = new FutureTask(new Callable() {
@Override
public String call() throws Exception {
while (!task.isCancelled()) {
System.out.println("Running...");
Thread.sleep(1000);
}
return "The End";
}
});
public static void main(String[] args) throws InterruptedException {
new Thread(task).start();
Thread.sleep(1500);
task.cancel(false);
}
The task is started, and after 1.5 iterations told to stop. It will continue sleeping (which it would not if you interrupted it) and then finish.