Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Interrupting a blocked thread

There are times when a thread blocks—such as when it is waiting for input—and it cannot poll a flag as it does in the previous example. In these cases, you can use the Thread.interrupt( ) method to break out of the blocked code:

//: c13:Interrupt.java
// Using interrupt() to break out of a blocked thread.
import java.util.*;

class Blocked extends Thread {
  public Blocked() {
    System.out.println("Starting Blocked");
    start();
  }
  public void run() {
    try {
      synchronized(this) {
        wait(); // Blocks
      }
    } catch(InterruptedException e) {
      System.out.println("Interrupted");
    }
    System.out.println("Exiting run()");
  }
}

public class Interrupt {
  static Blocked blocked = new Blocked();
  public static void main(String[] args) {
    new Timer(true).schedule(new TimerTask() {
      public void run() {
        System.out.println("Preparing to interrupt");
        blocked.interrupt();
        blocked = null; // to release it
      }
    }, 2000); // run() after 2000 milliseconds
  }
} ///:~

The wait( ) inside Blocked.run( ) produces the blocked thread. When the Timer runs out, the object's interrupt( ) method is called. Then the blocked reference is set to null so the garbage collector will clean it up (not necessary here, but important in a long-running program).

  • + Share This
  • 🔖 Save To Your Account