More on Threading

This lesson discusses selective interview topics on multithreading.

We'll cover the following...

Question # 1

How can we interrupt threads?

The thread class exposes the interrupt() method which can be used to interrupt a thread that is blocked in a sleep() or wait() call. Note that invoking the interrupt method only sets a flag that is polled periodically by sleep or wait implementation to know if the current thread has been interrupted. If so an interrupted exception is thrown.

Below is an example, where a thread is initially made to sleep for an hour but then interrupted by the main thread.

Press + to interact
class Demonstration {
public static void main( String args[] ) throws InterruptedException {
InterruptExample.example();
}
}
class InterruptExample {
static public void example() throws InterruptedException {
final Thread sleepyThread = new Thread(new Runnable() {
public void run() {
try {
System.out.println("I am too sleepy... Let me sleep for an hour.");
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ie) {
System.out.println("The interrupt flag is cleard : " + Thread.interrupted() + " " + Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
System.out.println("Oh someone woke me up ! ");
System.out.println("The interrupt flag is set now : " + Thread.currentThread().isInterrupted() + " " + Thread.interrupted());
}
}
});
sleepyThread.start();
System.out.println("About to wake up the sleepy thread ...");
sleepyThread.interrupt();
System.out.println("Woke up sleepy thread ...");
sleepyThread.join();
}
}

Take a minute to go through the output of the above program. Observe the following:

  • Once the interrupted exception is thrown, the interrupt status/flag is cleared as the output of line-19 shows.

  • On line-20 we again interrupt the thread and no exception is thrown. This is to emphasize that merely calling the interrupt method isn't responsible for throwing the interrupted exception. Rather the implementation should periodically check for ...