Thread interruption in Java

In our overview of thread methods, we saw various methods that throw InterruptedException.

Interruption is a mechanism whereby a thread that is waiting (or sleeping) can be made to prematurely stop waiting.

Incidentally, it is important not to confuse thread interruption with either software interrupts (where the CPU automatically interrupts the current instruction flow in order to call a registered piece of code periodically— as in fact happens to drive the thread scheduler) and hardware interrupts (where the CPU automatically performs a similar task in response to some hardware signal).

To illustrate interruption, let's consider again a thread that prints a message periodically. After printing the message, it sleeps for a couple of seconds, then repeats the loop:

Runnable r = new Runnable() {
  public void run() {
    try {
      while (true) {
        Thread.sleep(2000L);
        System.out.println("Hello, world!");
      }
    } catch (InterruptionException iex) {
      System.err.println("Message printer interrupted");
    }
  }
};
Thread thr = new Thread(r);
thr.start();

The InterruptedException is thrown by the Thread.sleep() method, and in fact by a few other core library methods that can "block", principally:

In general, InterruptedException is thrown when another thread interrupts the thread calling the blocking method. The other thread interrupts the blocking/sleeping thread by calling interrupt() on it:

thr.interrupt();

Provided that the thread or task calling sleep() (or whatever) has been implemented properly, the interruption mechanism can therefore be used as a way to cancel tasks.

Next: interruption during non-blocking calls and InterruptionException

On the next page, we'll look at a couple of further details that we haven't covered in the basics above: