Follow on Facebook

Like and Share on Facebook

Friday, January 30, 2015

Sleep method in java


Sleep method in java

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

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:
  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example sleep method in java

class TestSleepMethod1 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[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();  
   
  t1.start();  
  t2.start();  
 }  
}  

Output:1
1
2
2 3
4
3 4 5
5

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.

No comments:

Post a Comment