![]() |
VOOZH | about |
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.
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.
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:
Example 1: Using Thread.sleep() Method for Main Thread
Output:
0 1 2 3 4Explanation: 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 4Explanation: 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
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.