Home » Java Basics » 06 - Threads and GUIs
6

Thread sleep() and interrupt()

How to use the thread sleep and interrupt

The static method 'sleep' makes the current thread stop execution for the amount of time specified in its input parameter. The unit of time used is milliseconds (a millisecond is 1/1000 of a second). A checked exception called 'InterruptedException' is thrown by the sleep() method if another process attempts to interrupt the thread before the specified time-interval is over. This Exception should be handled when the sleep method is used.

public class HelloWorldThread extends Thread {
 
public void run() {
System.out.println("Hello World From Thread ");
}
 
public static void main(String args[]) {
(new HelloWorldThread()).start();
System.out.println("Hello World from Main Thread");
try {
sleep(2000);
}
catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
System.out.println("Hello World from main Thread Again...");
}
}

The HelloWorldThread would now print two messages from its main thread. One message is displayed right away. The sleep method makes the main method's thread stop execution for two seconds and the other message is displayed after these two seconds. Meanwhile, the other thread continues to execute and finishes before the main thread. If you try to put the entire try-catch section in the run() method of the other thread, the other thread will halt execution for two seconds.

The interrupt mechanism works through an interrupt status flag. If this flag is set for thread A from any other thread, thread A's sleep method is interrupted and an Interrupted Exception is thrown:

public class HelloWorldThread extends Thread {
 
public void run() {
System.out.println("Hello World from Thread ");
try {
sleep(2000);
}
catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
System.out.println("Hello World from Thread Again");
}
 
public static void main(String args[]) {
Thread t = new HelloWorldThread();
t.start();
System.out.println("Hello World from Main Thread");
t.interrupt();
}
 
}

The main thread in the above sample interrupts a new thread 't' before the 2 seconds is up. If you run the code, a "thread interrupted" message will be displayed right after "Hello World from Thread". The "Hello World From Thread Again" message will be printed out right away, and not after two seconds.