Thread.sleep() Method in Java With Examples
Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. The sleep() method is used to stop the execution of the current thread(whichever might be executing in the system) for a specific duration of the time and after that time duration gets over, the thread which is executing earlier starts to execute again.
Important Point Regarding Thread.sleep() Method:
- Method Whenever Thread.sleep() functions to execute, it always pauses the current thread execution.
- If any other thread interrupts when the thread is sleeping, then InterruptedException will be thrown.
- If the system is busy, then the actual time the thread will sleep will be more as compared to that passed while calling the sleep method and if the system has less load, then the actual sleep time of the thread will be close to that passed while calling sleep() method.
Syntax of Sleep() Method
There are 4 variations of the sleep() method in Java Thread. These are:
1. public static void sleep(long millis)throws InterruptedException 2. public static void sleep(long millis)throws IllegalArguementException 3. public static void sleep(long millis, int nanos)throws InterruptedException 4. public static void sleep(long millis, int nanos)throws IllegalArguementException
Parameters Passed In Thread.Sleep() Method