Monday 3 March 2014

Get the state of a thread : getState()

public Thread.State getState()
Returns the state of this thread.

Example
class ThreadStateEx extends Thread{
 public void run(){
  try{
   Thread.currentThread().sleep(500);
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[])throws Exception{
  ThreadStateEx t1 = new ThreadStateEx();
  ThreadStateEx t2 = new ThreadStateEx();
  ThreadStateEx t3 = new ThreadStateEx();

  t1.start();
  t2.start();
  t3.start();

  System.out.println("Thread1 state is " + t1.getState());
  System.out.println("Thread2 state is " + t2.getState());
  System.out.println("Thread3 state is " + t3.getState());

  t1.join();
  t2.join();
  t3.join();

  System.out.println("Thread1 state is " + t1.getState());
  System.out.println("Thread2 state is " + t2.getState());
  System.out.println("Thread3 state is " + t3.getState());
 }
}

Output   
Thread1 state is TIMED_WAITING
Thread2 state is TIMED_WAITING
Thread3 state is TIMED_WAITING
Thread1 state is TERMINATED
Thread2 state is TERMINATED
Thread3 state is TERMINATED


Thread State                                                 Wait & notify in Object class                                                 Home

No comments:

Post a Comment