Java Thread sleep() method

21 Mar 2025 | 2 min read

The sleep() method of thread class is used to sleep a thread for the specified amount of time.

Syntax

Parameter

Return

Throws

IllegalArgumentException: If the value of millis is negative or the value of nanos is not in the range 0-999999.

InterruptedException: If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Example 1

Output:

 1 1 2 2 3 3 4 4 5 5 

As you know that at a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up another thread and so on.

Example 2: when sleep time is negative

Output:

 Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.IllegalArgumentException: timeout value is negative	at java.lang.Thread.sleep(Native Method)	at SleepExp2.run(SleepExp2.java:9) java.lang.IllegalArgumentException: timeout value is negative	at java.lang.Thread.sleep(Native Method)	at SleepExp2.run(SleepExp2.java:9)