Search⌘ K

More on Threading

Explore how to handle thread interruptions in Java by understanding the interrupt status flag and the differences between Thread.interrupted and isInterrupted methods. This lesson helps you learn to manage thread signals correctly to prevent execution timeouts.

We'll cover the following...
1.

How can we interrupt threads?

Show Answer
Did you find this helpful?
Java
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 ...