Reputation: 2614
I'm writing a scheduler which accepts a Runnable
which is either queued for synchronous or asynchronous execution.
I would like to be able to implement a SomeScheduler.interrupt(int taskId)
which causes a InterruptedException()
to be thrown from within the thread.
Is this possible or am I going about this all wrong?
Upvotes: 2
Views: 2922
Reputation: 8310
Thread
s can be interrupted, a Runnable
is just class that implements the run method.
On it's own it doesn’t belong to a thread, if you want to interrupt the execution of the runnable you need to interrupt it's calling thread.
The typical way this is done is to use an ExecutorService
. When you submit a runnable or callable to the executor service it will return a Future
you can then interrupt a particular task by using the Future#cancel
method.
Note that simply interrupting the thread doesn’t cause InterruptedException
to be thrown unless the thread is running code that checks the interrupt status and throws InterruptedException
, for example the Thread#sleep
method.
Upvotes: 2