• sleep ( ) method in java is used to sleep a thread for an specified period of time.
  • Thread scheduler puts the current executing thread to non-runnable state or blocked state when sleep ( ) method in invoked.
  • Once the specified period of time is over, thread state is changed to runnable state and wait for CPU (processor) for further execution.
Syntax of sleep ( ) method in java

Thread class provides two methods for sleeping a thread for a specified period of time. They are as under:

  • public static void sleep ( long milliseconds ) throws InterruptedException
  • public static void sleep ( long milliseconds, int nanos ) throws InterruptedException
Example to implement sleep ( ) method in java
class Sample extends Thread { public void run() { for(int i=1;i<=5;i++) { try { Thread.sleep(5000); }catch(InterruptedException e) { System.out.println(e); } System.out.println(i); } }
public static void main(String args[]) {
Sample t1=new Sample();
Sample t2=new Sample();
t1.start();
t2.start(); } }

Output:

1
1
2
2
3
3
4
4
5
5

NOTE: At a time only one thread is executed and if we sleep a thread for specified period of time then the thread scheduler starts executing another thread and so on.