Thread Sleep in Java: Thread.sleep() Method
Sometimes we need to make a thread sleep for a particular period of time. For this, we use the sleep() method in Java program. The sleep() method is a static method provided by the Java Thread class so it can be called by its class name.
The Thread.sleep() is used to sleep a current thread for a specified amount of time. It always pauses the current thread for a given period of time. The sleep() method controls the behavior of thread and transition of thread from one state to another.
When the sleep() method is called on Thread object, the thread is become out of the queue and enters into blocked (or non-runnable state) for a specified amount of time.
When the specified amount of time is elapsed, the thread does not go into the running state (execution state) immediately. It goes into the runnable state (ready state) until it is called by Thread scheduler of JVM. Look at the below figure.
Thread class provides two variations of sleep() methods for sleeping a thread. The general form of sleep() method in Java is as follows:
public static void sleep(long milliseconds) throws InterruptedException
public static void sleep(long milliseconds, int nanoseconds) throws InterruptedExceptionIn the above syntax, the parameter milliseconds specify the length of time to sleep in milliseconds from 0 to 2^31 – 1. The second parameter nanoseconds specifies the additional time in nanoseconds from 0 to 999999.
The sleep() method can throw an exception named InterruptedException when interrupted in a program. Therefore, using sleep() method needs either we throw InterruptedException to the caller or the call to sleep() method must be enclosed in Java try-catch block otherwise, the program will not complete.
The general syntax to enclose sleep method in the try-catch block is given below:
try
{
Thread.sleep(1000); // sleeps a thread for at least 1000 milliseconds (1 sec).
}
catch(InterruptedException ie)
{
// catch handler.
}If the sleep time is negative, the Thread.sleep() method will throw an exception named IllegalArgumentException.
How to Sleep Current Thread in Java?
Let’s take an example program in which we will pause a child thread for a specified amount of time.
Example 1:
public class A implements Runnable {
public void run()
{
System.out.println("Hello");
try
{
Thread.sleep(2000); // Pausing running thread for 2 sec.
}
catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
System.out.println("Java");
System.out.println(Thread.currentThread());
}
void m1()
{
System.out.println("m1 method");
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "Child Thread");
t.start();
System.out.println("Number of active threads: " +Thread.activeCount());
a.m1();
}
}Output:
Number of active threads: 2
Hello
m1 method
Java
Thread[Child Thread,5,main]Explanation:
1. In this example program, there are two threads in the active state. One is the main thread and other is t. Therefore, number of active threads is 2.
2. When start() method is called by Thread t, the thread t enters into the runnable state.
3. When Thread scheduler of JVM selects it, it starts execution by calling the run() method implicitly. Inside the run() method, line no. 5 is executed.
After execution, the sleep() method is called and Thread t goes to sleep for 2000 milliseconds (2000 ms = 2 sec). Meanwhile, the scheduler selects the main thread for execution. JVM calls m1() method and prints the statement “m1 method” on the console.
4. When sleep time (2 sec) of thread t is elapsed, the thread t goes to the runnable state and then enters into running state when the scheduler selects it. Now, the remaining statements inside the run() method are executed.
5. When statements inside the run() method is completely executed, the thread t (child thread) is terminated normally.
Interruption of Thread.sleep() Method
Let’s create a Java program in which we will interrupt sleep method. Due to which sleep() method will not successfully execute and it will throw InterruptedException object that will be handled by the corresponding catch block.
Example 2:
public class A implements Runnable {
public void run()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("Hello Java");
System.out.println(Thread.currentThread());
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "Child Thread");
t.start();
t.interrupt();
}
}Output:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at threadEx.A.run(A.java:9)
at java.lang.Thread.run(Unknown Source)
Hello Java
Thread[Child Thread,5,main]Explanation:
1. When sleep() method is called on a thread t inside run() method, the thread t goes to sleep for 2000 ms. When thread t enters into the sleep state, meanwhile, thread scheduler selects the main thread for execution.
2. Now, the main thread starts execution from the statement t.interrupt();. This statement interrupts the sleep() method. Due to which sleep() method is not successfully executed and throws InterruptedException object. This exception is handled and caught by the corresponding Java try-catch block.
3. Finally, the remaining statement inside run() method is executed and thread t is terminated normally.
Context Switching between Multiple Threads Using Thread.sleep() Method
To perform multiple tasks in a program, we create multiple threads by creating multiple thread objects and attach different tasks to them. The context switching among threads can be done by calling sleep() method.
Let’s create a Java program in which we will create two threads t1, t2, and two tasks will perform by allocating them. Look at the program code to understand better.
Example 3:
public class A implements Runnable {
public void run()
{
for(int i = 1; i <= 3; i++)
{
try {
Thread.sleep(500);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println(Thread.currentThread() + " I: " +i);
}
}
public static void main(String[] args)
{
A a1 = new A();
Thread t1 = new Thread(a1, "First Child Thread");
A a2 = new A();
Thread t2 = new Thread(a2, "Second Child Thread");
t1.start();
t2.start();
}
}Output:
Thread[First Child Thread,5,main] I: 1
Thread[Second Child Thread,5,main] I: 1
Thread[Second Child Thread,5,main] I: 2
Thread[First Child Thread,5,main] I: 2
Thread[Second Child Thread,5,main] I: 3
Thread[First Child Thread,5,main] I: 3Explanation:
1. In this example program, three threads are in active state. One is main thread and two child threads t1 and t2 that are created from main thread.
2. Since we are performing two tasks in this program, we have created two task objects a1 and a2 inside the main method.
3. To perform two tasks, we have created two threads t1 and t2 and two tasks are allocated to them.
4. Inside for loop of run() method, Thread.sleep(500); method is called. Since it is a static method so we can call by its class name.
5. The argument inside the sleep() method pauses the current thread for the specified amount of time in which it is invoked.
6. First, main thread starts execution. When t1.start() method is called, thread t1 goes to runnable state (ready for execution).
7. When thread scheduler selects t1 for execution, it enters into running state and starts execution. sleep() method is called inside for loop and JVM pauses the thread t1 for 500 milliseconds. Now, the control goes back to main thread.
8. Now, t2 is ready for execution. When sleep method is encountered during the execution of thread t2, t2 goes to sleep for 0.5 sec and control of execution jumps back to main.
9. Meanwhile, t1 completes its sleep, and control of execution again goes to t1. This process continues until the run() method gets complete execution. Thus, the control switches among main thread, t1, and t2.
In this tutorial, you learned how to pause the current thread in Java using the sleep() method provided by the Thread class. You also gained an understanding of the InterruptedException that occurs when the sleep() method is interrupted.
I hope this tutorial has helped you to grasp this important Java concept. Stay tuned for the next tutorial, where we’ll explore the yield() method in Java with examples.
Thank you for reading!!!








