One of the most suggested ways to pause a thread is to extend the Runnable interface by adding a pause() method:
interface RunnablePausable extends Runnable {
public void pause();
}
This never made sense to me since you don't actually want to pause the runnable but the Thread that runs it, in the same way you start/interrupt a Thread, not a Runnable.
A more elegant approach: since the interrupt() functionality is well built-in and supported by multiple methods, what if we interrupt() a Thread not just to terminate it, but for a general request instead (like you would interrupt a CPU, in a way)? And then let the Runnable handle this specific request
As an example: interrupt() the thread and, instead of straight up terminating it, handle its request to pause, stop, resume, or do anything else you like.
Not sure if this makes sense.
Something like this:
public void run() {
try {
//...
} catch (InterruptedException ie) { //interrupted
if (i_wanted_to_pause) { //manage request
//wait
}
if (i_wanted_to_stop) {
//return
}
if (any_other_request) {
//handle it
}
}
}
And:
public void run() {
if (Thread.currentThread().isInterrupted()) { //interrupted
if (request_to_pause) { //manage request
//wait
}
if (request_to_stop) {
//return
}
if (any_request) {
//handle it
}
}
}
Now the problem is: how to make a specific request to the interrupted thread?
How can I communicate my request to the interrupted thread, as if was meant to stop, pause, or do anything else?
Ideas:
- Subclass InterruptedException into InterruptedExceptionStop and InterruptedExceptionPause (no idea how I can throw them)
- Create a separate object containing the request. Don't know what would be the best way to achieve this without over-complicating things
- Other?