- 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.
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
- 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.
1.Using Thread.Sleep() Method For Main Thread
import java.io.*;
import java.lang.Thread;
class GFG {
public static void main(String[] args)
{
try {
for (int i = 0; i < 5; i++) {
// it will sleep the main thread for
1 sec
// ,each time the for loop runs
Thread.sleep(1000);
// printing the value of the variable
System.out.println(i);
}
}
catch (Exception e) {
// catching the exception
System.out.println(e);
}
}
}
Output
0
1
2
3
4
2. Using Thread.Sleep() Method For Custom Thread
import java.io.*;
import java.lang.Thread;
class GFG extends Thread {
public void run()
{
try {
for (int i = 0; i < 5; i++) {
// it will sleep the main
thread for 1 sec
// ,each time the for loop
runs
Thread.sleep(1000);
System.out.println(i);
}
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args)
{
// main thread
GFG obj = new GFG();
obj.start();
}
}
Output
0
1
2
3
4
3.IllegalArguementException When Sleep Time Is Negative
import java.io.*;
import java.lang.Thread;
class GFG {
public static void main(String[] args)
{
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(-100);
System.out.println(i);
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
java.lang.IllegalArgumentException:
timeout value is negative