Thread sleep

Making a thread sleep means pausing its execution for some specified amount of time.
Java provides 2 methods in which a thread execution can be paused and this article will discuss both of them.

Method 1: Thread.sleep() method
java.lang.Thread class has a sleep method which pauses a thread from executing for a given amount of time. There are two overloaded versions of sleep method explained below.
1. sleep(long milliseconds) : This method accepts a long value as argument and pauses the current thread for given number of milliseconds.
Thus, sleep(2000) will pause the current thread for 2 seconds.
2. sleep(long milliseconds, int nanoseconds) : This method is used to pause the current thread for given number of milliseconds plus the given nanoseconds.

Thread.sleep() example
Below is an example program showing the use of sleep() method.
It determines the start time, pauses the current thread for 3 seconds and then determines the end time.
Both the times are printed at console.

public class ThreadSleepExample { 
  public static void main(String[] args) { 
    try { 
      // get start date and time 
      long startTime = System.currentTimeMillis(); 
      Date date = new Date(startTime); 
      System.out.println("Start Time: " + date); 
      // pause current thread for 3 seconds 
      Thread.sleep(3000); 
      // get end date and time 
      long endTime = System.currentTimeMillis(); 
      Date endDate = new Date(endTime); 
      System.out.println("End Time: " + endDate); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    } 
  } 
}

Output of the program is

Start Time: Sun Sep 15 16:28:54 IST 2019
End Time: Sun Sep 15 16:28:57 IST 2019

Note that there is an exact difference of 3 seconds in the start and end times but it may not always be the case.

Learn more about threads in java here.

There will be a difference of at least the given sleep time but it may also be more than that. Reason is explained in the pointers ahead.

Below points should be remembered regarding sleep method.

  1. sleep() pauses the current executing thread.
    Current executing thread means the thread in which sleep method is called.
  2. sleep() is a static method. You do not need an instance of thread to call sleep.
  3. After the sleep time is over, the thread is put to runnable state which means that it is ready for execution. It may or may not immediately start executing after the sleep time.
    It depends on the thread schedulers of the JVM and this is the reason why waiting time of a thread may be more than the sleep time.
  4. Thread that is put to sleep does not release any object locks if it holds lock(s) for object(s) at the time sleep() is called.
  5. You can also call sleep() in main method.
  6. If some other thread interrupts a sleeping thread, then java.lang.InterruptedException is thrown.
    This is also evident from the signature of sleep which declares to throw this exception.

Method 2: Using TimeUnit
Java 5 introduced java.util.concurrent.TimeUnit.
It is an enum which contains values for different time units. It also has a sleep method which takes a long as argument denoting the amount of time to sleep. Example,

 

import java.util.concurrent.TimeUnit; 

public class ThreadSleepExample { 
  public static void main(String[] args) { 
    try { 
      // get start date and time 
      long startTime = System.currentTimeMillis(); 
      Date date = new Date(startTime); 
      System.out.println("Start Time: " + date); 
      // pause current thread for 3 seconds 
      TimeUnit.SECONDS.sleep(3000); 
      // get end date and time 
      long endTime = System.currentTimeMillis(); 
      Date endDate = new Date(endTime); 
      System.out.println("End Time: " + endDate); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    } 
  } 
}

This method has an advantage as compared to previous one that here you can directly specify the time unit for which you want the thread to pause its execution.
That is, you can make it to sleep for given seconds, milliseconds, minutes and so on, while in Thread.sleep() method, you have to convert the amount of sleep time to milliseconds.
Thus,

TimeUnit.SECONDS.sleep(2);              // pause thread for 2 seconds
TimeUnit.MILLISECONDS.sleep(5);    // pause thread for 5 milliseconds
TimeUnit.HOURS.sleep(1);                 // pause thread for 1 hour

while the same using Thread.sleep will be written as

Thread.sleep(2000);             // pause thread for 2 seconds
Thread.sleep(5);                   // pause thread for 5 milliseconds
Thread.sleep(3600000);      // pause thread for 1 hour

The difference in two methods is evident from the examples above.

sleep() method of TimeUnit also internally calls sleep method of java.lang.Thread class.
Hope the article was useful.

Leave a Reply