AdSense

AdSense3

Friday 26 September 2014

Sleep method in java AND Can we start a thread twice?

The sleep() method of Thread class is used to sleep a thread for the specified amount 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 of sleep method in java

  1. class TestSleepMethod1 extends Thread{  
  2.  public void run(){  
  3.   for(int i=1;i<5;i++){  
  4.     try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
  5.     System.out.println(i);  
  6.   }  
  7.  }  
  8.  public static void main(String args[]){  
  9.   TestSleepMethod1 t1=new TestSleepMethod1();  
  10.   TestSleepMethod1 t2=new TestSleepMethod1();  
  11.    
  12.   t1.start();  
  13.   t2.start();  
  14.  }  
  15. }  
Output:
       1
       1
       2
       2
       3
       3
       4
       4
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.


Can we start a thread twice

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
  1. public class TestThreadTwice1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("running...");  
  4.  }  
  5.  public static void main(String args[]){  
  6.   TestThreadTwice1 t1=new TestThreadTwice1();  
  7.   t1.start();  
  8.   t1.start();  
  9.  }  
  10. }  
       running
       Exception in thread "main" java.lang.IllegalThreadStateException

No comments:

Post a Comment