Sleep method in java Code Example

Last Updated On Tuesday 28th Sep 2021

Java Sleep

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

Provides two methods

  • public static void sleep(long milliseconds)throws InterruptedException
  • public static void sleep(long milliseconds, int Nanos)throws InterruptedException
	 public class SleepMethod extends Thread {
   public void run() {
     for (int i = 1; i < 5; i++) {
       try {
         Thread.sleep(500);
       } catch (InterruptedException e) {
         System.out.println(e);
       }
       System.out.println(i);
     }
   }
   public static void main(String args[]) {
     SleepMethod t1 = new SleepMethod();
     SleepMethod t2 = new SleepMethod();

     t1.start();
     t2.start();
   }
 }
	

OutPut

	1
1
2
2
3
3
4
4