Java Thread.sleep() Method Deep Dive with Examples

This article has been revised to ensure it is up-to-date with the latest Java JDK 21, guaranteeing its completeness and relevance.

If you want to pause (temporarily cease) a particular thread in Java from executing, you can make use of the sleep() static method from the Thread class from java.lang package.



When you peek into the java.lang.Thread class, you will see that you have three overloaded sleep() methods to choose from.

  1. public static void sleep(long millis) throws InterruptedException
  2. public static void sleep(long millis, int nanos) throws InterruptedException
  3. public static void sleep(Duration duration) throws InterruptedException


Some key points to make a note about the sleep methods.

  1. They are static methods, hence belong to the class and are invoked using Thread.sleep().
  2. They do not return any value (void).
  3. Throws a InterruptedException.


Let's take a look at each of them one-by-one with examples.


1. sleep(long millis)


2. sleep(long millis, int nanos)


3. void sleep(Duration duration)


Example of InterruptedException:


Take-aways:

List of Thread.sleep() methods as of Java JDK 21

Reference:

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!