I want to interrupt a thread which is checking for the interrupted flag in each increment of an endless while loop. The only way to exit the loop is by throwing an InterruptedException.
Somewhere in the (inaccessible) code executed by the interruptable thread, a sleep operation is declaring an InterruptedException and a catch block where the exception is swallowed. In an unfortunate case, the thread will be interrupted while the sleep method is being executed, causing the interrupted flag to be reset. In such a case, the thread won't exit the endless while loop.
What would be the best strategy to avoid such a situation? My main thread in the code below calls interrupt in a loop until the interruptable thread is not alive anymore. Is it a reasonable strategy? What are the alternatives?
public class InterruptableThreads extends Thread {
public static Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
try {
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Swallowing exception. Resetting interrupted flag");
}
System.out.println("t1 run");
}
} catch (InterruptedException e) {
System.err.println("t1 interrupted.");
}
}
});
public static void main(String[] args) throws InterruptedException {
t1.start();
Thread.sleep(4000);
while (t1.isAlive()) {
t1.interrupt();
}
t1.join(1000);
System.out.println("Finished!");
}
}