VOOZH about

URL: https://www.geeksforgeeks.org/java/thread-sleep-method-in-java-with-examples/

⇱ Java Thread.sleep() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Thread.sleep() Method

Last Updated : 24 Apr, 2026

The Thread.sleep() method in Java is used to pause the execution of the currently running thread for a specified amount of time. After the sleep duration ends, the thread becomes runnable again and continues execution based on thread scheduling.

  • Throws InterruptedException if another thread interrupts during sleep.
  • Actual sleep duration may vary based on system load; higher load increases sleep time.

Output:

0 1 2

Explanation: The main thread prints numbers from 0 to 2, and after each print, Thread.sleep(1000) pauses execution for 1 second. This results in a visible delay between each output.

Syntax

There are 2 variations of the sleep() method in Java Thread. These are:

public static void sleep(long millis)
public static void sleep(long millis, int nanos)

Parameters:

  • millis: Duration of time in milliseconds for which thread will sleep
  • nanos: This is the additional time in nanoseconds for which we want the thread to sleep. It ranges from 0 to 999999..

Common Examples of Thread.sleep()

Example 1: Using Thread.sleep() Method for Main Thread 

Output:

0 1 2 3 4

Explanation: The main thread runs the loop and prints numbers from 0 to 2, pausing for 1 second after each print using Thread.sleep(1000). After the pause, the thread resumes execution and continues the loop.

Example 2: Using Thread.sleep() method for Custom thread 

Output:

0 1 2 3 4

Explanation: MyThread extends the Thread class and overrides the run() method to print numbers from 0 to 4, pausing for 1 second in each iteration using Thread.sleep(1000). The sleep call is wrapped in a try-catch block to handle InterruptedException, after which the thread resumes execution.

Example 3: IllegalArgumentException when sleep time is Negative


Output
java.lang.IllegalArgumentException: timeout value is negative

Explanation: Passing a negative value to Thread.sleep() is invalid, so Java immediately throws an IllegalArgumentException. This ensures that the sleep duration is always non-negative.

Comment