A single program or application is the combination of several small operations or tasks performed behind the scenes. These small chunks of code or operation are referred to as threads. There can be more than one thread running to perform a single task at the same time.

Most of the time these threads are dependent on each other like thread number “5” requires the value that is generated by thread number “1”. This dependency creates bottlenecks and deadlocks which leads to the blockage of an entire program working. To resolve these issues, some thread execution needs to be blocked for specific time intervals. This blocking or halting the execution of a thread is done using the “Thread.sleep()”.

This guide explains the working and implementation of the Thread.sleep() method in Java:

How to Use the Thread.sleep() Method in Java?

The “sleep()” method of a “Thread” class interacts with the threads and allows users to stop the working of specified threads. This method sleeps the thread and stops its execution for the provided milliseconds. Once the provided time ends, the slept thread moves to the “Runnable state”(ready state) and gets executed when called by the Thread scheduler of JVM.

Syntax

There are two syntaxes for the “Thread.sleep()” method which are mentioned below:

  • The first syntax accepts a single parameter of time in milliseconds:
public static void sleep(long milliseconds)throws InterruptedException
  • The second syntax accepts an additional parameter of time in nanoseconds:
public static void sleep(long milliseconds, int nanos)throws InterruptedException

Important Points to Remember for Java Thread.sleep() Method

Some key points to remember while dealing with the “Thread.sleep()” method are listed below:

  • It always stops the execution cycle for currently executing threads. This method saves the state of the current thread and when awake the OS executes it from the point where it slept. 
  • The execution time for a new thread is almost equal to the provided time. However, if the system is busy then, the sleeping time increases to the provided one.
  • The “InterruptedException” is thrown whenever the new thread interrupts the currently sleeping thread.
  • The “Thread.sleep()” method throws an “IllegalArgumentException” when a user tries to pass “negative” values.
  • Use the “start()” and “interrupt()” methods to start and stop the execution of a current thread respectively.

Let’s consider below Java examples to implement the working of a Thread.sleep() method.

Example 1: Applying Thread.Sleep() Method on Main Thread 

In this example, the currently executing Thread is suspended from the “main()” method using the “Thread.sleep()” method. There is a usage of the “try/catch” block as well to handle the “InterruptedException”:

public class Threadsleep {
public static void main(String[] args)//Settingup the try/catch blocks
{
try {
  System.out.println("Running the Thread After Specific Time Period Using Thread.sleep(): ");
  int i = 0;
  while ( i < 10 ) {
  Thread.sleep(1000);
  System.out.println(i);
  i = i + 2;
  }
}
catch (InterruptedException excep) {
  System.out.println(excep);
}
}
}

The above code snippet:

  • Use the “try” block which contains a “while” loop that iterates till the value of iteration reaches “10”. The execution of this loop halts for “1000” milliseconds or 1 second using the “Thread.sleep()” method. This loop then prints the current iteration numbers on the console after halting ends. 
  • After that, use the “addition” operator to increment the iteration number by a factor of “2” each time.
  • Finally, use the catch block to handle the “InterruptedException”.

The generated output for the main code confirms the halting of a Thread for a specified time interval:

How to Achieve Multithreading Using Thread.sleep() Method in Java?

A “Multithreading” allows the operating system to execute more than one thread alternatively at the same time. This process saves a lot of time and each executing threads need to be independent to gain loose coupling(Low Interdependencies between Modules). In the multithreading process, chosen threads are slept for specific time intervals and executing awakened threads. The “Thread.sleep()” method is used in this process to sleep the chosen threads, as portrayed below:

class multiThreader extends Thread{
public void run()
{
  int i = 0;
  while ( i < 10 ) {
  System.out.println("\nCurrently Working Thread Name: " + currentThread().getName());  try {
  sleep(1500);
  } catch (Exception ex) {
  System.out.println("Raised Exception Details: " + ex);
  }
  i = i + 2;
  }
}
}

public class Threadsleep {
public static void main(String[] args) {
  multiThreader thread1 = new multiThreader();
  multiThreader thread2 = new multiThreader();
  multiThreader thread3 = new multiThreader();
 
  thread1.start();
  thread2.start();
  thread3.start();
}
}

The mentioned code executes like this:

  • First, define a class “multiThreader” of the default system “Thread” class to inherit its properties.
  • Define a default “run()” method of the “Thread” class and place the “while” loop inside it that performs “10” iterations. Every iteration selects and displays the current thread and its allotted name on the console.
  • Invoke the “currentThread()” and “getName()” methods to retrieve the Thread and its name respectively.
  • Now, use the “try/catch” block and “sleep()” method to sleep the current thread for “1500” milliseconds.  Also, increment the iteration number by a factor of “2”.
  • Inside the “main()” method, create three instances for the already created “multiThreader” class. These instances act as the custom-build threads.
  • Invoke the “start()” method using these instances to start the execution of threads. 

The output shows two threads are being executed side by side:

How to Synchronize Multiple Threads Using the “Thread.sleep()” Method in Java?

The “Thread.sleep()” method helps in achieving the Synchronization (order of thread execution) for multiple threads. By sleeping the threads for specific time intervals similar to the Multithreading concept:

public class Threadsleep {
private static boolean taskCompleted = false;
public static class Thread1 extends Thread
{
  public void run() {
  while(!taskCompleted) {
    try {
    Thread.sleep(2000);
    } catch(InterruptedException excep) {
    System.out.println(excep);
    }
  }
  System.out.println("Task is Completed...");
  }
}//Define another Thread
public static class Thread2 extends Thread
{
  public void run() {
  System.out.println("Task is Under Completion...");  
  taskCompleted = true;
  }
}
public static void main(String[] args) {
  new Thread1().start();
  new Thread2().start();
}
}

Have a look at the working of the above code:

  • First, define a “boolean” type variable “taskCompleted” with the initial value of “false”.
  • Next, create a nested class named “Thread1” that inherits the properties of a default “Thread” class.  
  • Inside it, define a “run()” method which contains the “while()” loop. This loop executes the containing code till the “taskCompleted” variable returns “true”.
  • Next, use the “Thread.sleep()” method in the “try” block to sleep the current thread for “2000” milliseconds.
  • Then, define another thread named “Thread2” to set the value of a “taskCompleted” variable to “true”. 
  • Finally, create new objects for both threads and apply the “start()” method on them to start the thread execution.

The output shows that the first Thread sleeps for “2000” milliseconds till then the second Thread runs. After the specified time interval, the first thread gets executed:

Exceptions in Thread.sleep() Method

Two types of exceptions mainly occur while dealing with the “Thread.sleep()” method. The reason for their occurrence and practical implementation are explained below.

Exception 1: InterruptedException While Dealing With Thread.sleep() Method

The “InterruptedException” raises when the currently sleeping thread gets interrupted by another thread. This interruption is done by invoking the “interrupt()” method. The interruption breaks the execution cycle and halts the execution for the remaining part of a program. As demonstrated below:

public class Threadsleep {
public static class currThread extends Thread
{
  public void run() {
  try {
    Thread.sleep(2000);
    System.out.println("Thread is Awaken");
  }
  catch (InterruptedException excep)
  { 
    System.out.println("InterruptedException is Raised and the Details are:");
    excep.printStackTrace();
  }
  }
}
public static void main(String[] args) {
  currThread demoThread = new currThread();
  demoThread.start();
  demoThread.interrupt();
}
}

The above code works like this:

  • First, create a nested class “currThread” which inherits the properties of a System default “Thread” class. Inside this class, call the “Thread.sleep()” method to halt the execution of a current thread for a specified “2000” milliseconds time interval.
  • Then, utilize the “catch” block to handle the “InterruptedException”. In case of its occurrence, print the details of this exception like the line number and class name where it occurred. 
  • Finally, create an instance of the custom-created thread and start its execution using the “start()” method. Then, interrupt the slept thread by calling the “interrupt()” method.

The output confirms the occurrence of an exception due to the interruption of Thread:

Exception 2:  Raise of IllegalArgumentException While Dealing With Thread.sleep() Method

The “Thread.sleep()” method raises an “IllegalArgumentException” when the “negative” integer value is passed to it. Because time can never be negative that’s why this method always accepts the positive integer for sleeping the current Thread:

public class Threadsleep {
public static class currThread extends Thread
{
  public void run() {
  try {
    Thread.sleep(-1500);
    System.out.println("Thread is Awaken");
  }
  catch (InterruptedException excep)
  { 
    excep.printStackTrace();
  }
  }
}
public static void main(String[] args) {
  currThread demoThread = new currThread();
  demoThread.start();
}
}

In the above code snippet:

  • First, create a Thread “currThread” that sleeps for a “-1500” time interval using the “Thread.sleep()” method. But as this method does not accept the “negative(-)” value as an argument this leads to the “IllegalArgumentException”.
  • Catch this raised exception using the “catch” block and print its detail on the console.
  • Define the “main()” method that calls the “start()” method to start the “currThread” execution.

The output shows the occurrence of the mentioned exception:

Bonus Tip: The “wait()” Method | Alternative Approach of Thread.sleep()

To suspend the working of a current thread for a specific time interval the user can also use the “wait()” method. Its purpose of utilization is similar to the “Thread.sleep()” method. Their main difference is the way they suspend the working of the current thread. 

The “Thread.sleep()” method accepts milli or nanoseconds as an argument and suspends the working for the provided time interval. On the other hand, the “wait()” method halts the execution and it releases until another thread calls the “notify()” or “notifyAll()” methods. These methods are called on the thread holding the monitor lock or object and symbolize that the thread surrenders the lock soon.


Let’s re-implement, the previously done Synchronize Multiple Threads section using the “wait()” method:

Public class Threadsleep {
private static Object sharedObj = new Object();
private static boolean taskCompleted = false;
  public static class Thread1 extends Thread
{
  public void run() {
    while(!taskCompleted) {
      synchronized(sharedObj) {
        try {
          sharedObj.wait();
        } catch(InterruptedException e) {
       
        }
      }
    }
    System.out.println("\nThread 1 -> Task is Completed...");
  }
}//Define another Custom Thread
  public static class Thread2 extends Thread
{// Define the functionality of this Thread
  public void run() {
    System.out.println("Thread 2 -> Task is Under Completion...");     
    taskCompleted = true;
    synchronized(sharedObj) {
      sharedObj.notifyAll();
    }
  }
}
  public static void main(String[] args) {
  new Thread1().start();
  new Thread2().start();
}
}

The above code works like this:

  • First, declare a static type object “sharedObj” and a boolean type variable “taskCompleted” with the initial value of “false”.
  • Next, create a custom thread “Thread1” and define the default “run()” method. Inside this method, pass the “sharedObj” into the “synchronized()” method to prevent thread interference and memory errors. 
  • Then, apply the “wait()” method inside the “try/catch” block to handle the exceptions and print dummy text.
  • Next, create a custom thread “Thread1” and define the default “run()” method to pass the “sharedObj” into the “synchronized()” method. This “synchronized()” method prevents thread interference and memory errors.
  • Finally, create the constructors of both Threads “Thread1” and “Thread2”. Lastly, use the “start()” method next to these threads to start their execution.

The generated output confirms the thread synchronization using the “wait()” method. Moreover, the OS scheduler is used to set the sleep timer instead of hard-coded time intervals:

That’s all about the usage and implementation of the Thread.sleep() method in Java.

Conclusion

The “Thread.sleep()” method halts the execution of a current Thread for the specified time interval. It accepts only positive values as an argument in milliseconds or nanoseconds format. When the time ends, the “Thread.sleep()” method executes the halted thread from the same state. As an alternative approach, the user can use the “wait()” method which calls the “notify()” or “notifyAll()” methods to execute the halted Thread. This guide has illustrated the working and important key points for the “Thread.sleep()” method.