Saturday 1 March 2014

thread status isAlive

A Thread remains alive until it returns from the run() method, or or until the thread is abruptly stopped by the stop()method. Simply A thread is alive if it has been started and has not yet died. Stop method is deprecated.

Syntax
public final boolean isAlive()
returns true if this thread is alive; false otherwise.

isAlive() is a final method, so you can't override it. isAlive() method returns false before calling the start method

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
  }
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread thrd = new Thread(task);
  
  System.out.println("Thread before calling start " + thrd.isAlive());
  thrd.start();
  System.out.println("thread after calling start " + thrd.isAlive());
  
  try{
   thrd.join();
  }
  catch(InterruptedException e){

  }
  System.out.println("thread after finishes execution " + thrd.isAlive());
  System.out.println(thrd.isAlive());
 }
}
 

Output
Thread before calling start false
thread after calling start true
Thread name is Thread-0
thread after finishes execution false
false
   
Observation
See the output the isAlive() method returns false, before calling the start(). Sleep method makes the thread to wait for some time. join method waits until the thread on which it is called finishes execution. Don't worry much abut sleep() an join(), you will see more about these soon.



Thread constructors                                                 Thread sleep                                                 Home

No comments:

Post a Comment