- Here we are created our own Thread.sleep() in Java. It is an Util class which is use anywhere when sleep method is required.
- There are no requirement to create multiple time sleep method.
- The sleep() method is stop the execution of current thread to for a specific duration of the time and after that time duration gets over, the thread which is executing earlier starts to execute again.
- Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class.
The sleep() Method Syntax:
public static void sleep(long mls) throws InterruptedException
public static void sleep(long mls, int n) throws InterruptedException
class Util
{
static void sleep(long millis) {
try {
Thread.sleep(1000);
}catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
class Employee extends Thread {
public void run() {
for(int i=0;i<4;i++) {
System.out.println(i);
Util.sleep(1000);
}
}
}
public class SleepUtil {
public static void main(String[] args) {
Employee e1=new Employee();
e1.start();
for(int i=5;i<7;i++) {
System.out.println(i);
Util.sleep(1000);
}
}
}
Output :-
5
0
1
6
2
3