new Thread(() -> {
while(true) {
execute();
Thread.sleep(10 * 1000);
if(hasLoopedEnough)
return;
}
}).start();
Suppose I wanted to rewrite this using ScheduledExecutorService. In above code it's only the loop/thread itself that knows when to stop the process. But if I use
executor.scheduleWithFixedDelay(task, 0, 10, SECONDS);
How can I cancel this task from within the runnable itself?
CodePudding user response:
The method "scheduleWithFixedDelay" returns a ScheduledFuture<?> object. keep a reference to this object and use its "cancel" method. see documentation here: cancel method
this doesnt guarantee the task will be cancelled immediately, and it might also try to interrupt the thread (and cause it to throw an InterruptedException inside the thread) depending on the boolean flag you specify in the cancel method.
CodePudding user response:
We can cancel a task running on a dedicated Thread by invoking Thread.interrupt.This approach is applicable only if the application owns the thread, if the application is using a thread pool, the ExecutorService implementation not the application owns the threads. Thus we mustn't directly interrupt the worker threads in a pool.
public class CancelTaskWithInterruption {
public void startAndCancel() throws InterruptedException {
final Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
// Do some work.
}
System.out.println("Stopping...");
};
final Thread thread = new Thread(task);
thread.start();
TimeUnit.SECONDS.sleep(2); // Wait for some time
thread.interrupt();
}
}