Java Thread Sleep | Thread.sleep() Method

Java Thread sleep | Sometimes we need to make a thread sleep for particular period of time. For this, we use sleep() method in Java program.

The sleep() method is a static method provided by the Thread class so it can be called by its class name. It is used to sleep a 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 enter 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 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.

Java thread sleep

Thread class provides two variations of sleep() methods for sleeping a thread. The general form for sleep() method is as follows:

Syntax of sleep() method in Java:

public static void sleep(long milliseconds) throws InterruptedException
public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

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 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.
}

How to sleep Current Thread in Java?


Let’s take an example program where we will pause a child thread for specified amount of time.

Program source code 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 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 runnable state.

3. When Thread scheduler of JVM selects it, it starts execution by calling run() method implicitly. Inside run() method, line no. 5 is executed.


After execution, sleep() method is called and Thread t goes to sleep for 2000 ms (2000 ms = 2 sec). Meanwhile, 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 runnable state and then enters into running state when the scheduler selects it. Now, 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.

Let’s create a program where 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.

Program source code 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, 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 Multitple Threads using 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 program where we will create two threads t1, t2, and two tasks will perform by allocating them. Look at the source code to understand better.

Program source code 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: 3

Explanation:

Life cycle of thread t1 when sleep method is called on it

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.

Hope that this tutorial has covered important points related to Java thread sleep method with example program. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ Yield Method in Java⇐ PrevNext ⇒