More on Threading

This lesson discusses selective interview topics on multithreading.

We'll cover the following...
1.

How can we interrupt threads?

0/500
Show Answer
Did you find this helpful?
Press + to interact
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 ...