When using the ExecutorService
returned by Executors.newSingleThreadExecutor()
, how do I interrupt it?
A thread can send an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. This means interruption of a thread is caused by any other thread calling the interrupt() method. void interrupt() - Interrupts the thread.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing.
By calling Thread. currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
In order to do this, you need to submit()
a task to an ExecutorService
, rather than calling execute()
. When you do this, a Future
is returned that can be used to manipulate the scheduled task. In particular, you can call cancel(true)
on the associated Future
to interrupt a task that is currently executing (or skip execution altogether if the task hasn't started running yet).
By the way, the object returned by Executors.newSingleThreadExecutor()
is actually an ExecutorService
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With