How can I determine if a thread is alive?

Brandon Rohlfs

The thread class provides a method which can be called on an instance of a Thread to determine if it is currently executing. If isAlive() returns false the thread is either a new thread that is not currently executing or it is dead.

public boolean isAlive(); 

The following code creates a thread and executes it by calling it's start() method. Before the thread is started a test is performed to determine if the thread is currently executing. Since the thread is new, isAlive() returns false. You will also notice within the run() method a reference to the current thread is grabbed using the following method.

static Thread currentThread()
Since isAlive() is called within the run() method isAlive() returns true because the thread is executing at that time.

public class ThreadTest{
 public static void main(String[] args){
  T t = new T("T Thread");
  threadStatus(t.isAlive(),t.getName());
  t.start();
 }
 public static void threadStatus(boolean isalive, String tname){
  String status = isalive ? "is alive" : " is not alive"; 
  System.out.println(tname +""+  status);
 }
}

class T extends Thread{
 public T(String tname){
  super(tname); 
 }
 public void run(){
  Thread t = Thread.currentThread();
  String tname = t.getName();  
  boolean isalive = t.isAlive(); 
  for(int i = 0; i < 9; ++i){
   System.out.println(tname + " is alive ?" + " : " + isalive); 
  }
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact