- Motivation
- Basic threads
- Sharing limited resources
- Thread states
- Cooperation between threads
- Deadlock
- The proper way to stop
- Interrupting a blocked thread
- Thread groups
- Summary
- Exercises
Interrupting a blocked thread
There are times when a thread blockssuch as when it is waiting for inputand 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).