Getting the state of a thread (running, blocked, etc)

This becomes very simple with the new java.lang.management package in JDK 1.5. The following example starts up a Task thread and a Monitor Thread. The Monitor thread prints out the state of the Task thread every half a second. All possible thread states are documented in the API docs.

Main.java:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMBean;
import java.lang.management.ThreadState;
 
public class Main
{
   public static void main(String []args) {
      final Task t1 = new Task();
       
      t1.setName("Task Thread");
      t1.start();
       
      Thread monitorThread = new Thread() {
         public void run() {
            ThreadMBean mbean = ManagementFactory.getThreadMBean();
            ThreadInfo threadInfo1 = mbean.getThreadInfo(t1.getId());
 
            System.out.println("tMonitoring " + t1.getName() + " for 10 secondsn");
            System.out.println("tcountertstatettTotal CPU Time"); 
            for (int i=0; i<20; i++) {
               threadInfo1 = mbean.getThreadInfo(t1.getId());
               System.out.println("t" + t1.getCounter() + "t" + threadInfo1.getThreadState() + "  t" + 
                                  (mbean.getThreadCpuTime(t1.getId()) / 1000000) + " ms");
               
               try { Thread.sleep(500); } catch(Exception e) { }
            }
             
            t1.terminate();
         }
      };
       
      monitorThread.start();
   }
}
 
class Task extends Thread
{
   long counter = 0;
   private boolean terminated = false;
 
   public void run() {
      while (true) {
         if (terminated) return;
         
         counter++;
         for (int i=0; i<50000000; i++) { }
         try { Thread.sleep(100); } catch(Exception e) { }
      }
   } 
    
   public long getCounter() {
      return counter;
   }
    
   public void terminate() {
      terminated = true;
   }
}

outputs:

        Monitoring Task Thread for 10 seconds
 
        counter state           Total CPU Time
        1       Running         110 ms
        3       Sleeping        360 ms
        5       Sleeping        610 ms
        8       Running         911 ms
        10      Running         1211 ms
        12      Sleeping        1472 ms
        14      Sleeping        1712 ms
        17      Running         2012 ms
        19      Running         2313 ms
        21      Sleeping        2573 ms
        23      Sleeping        2824 ms
        26      Running         3104 ms
        28      Sleeping        3424 ms
        30      Sleeping        3675 ms
        33      Running         3965 ms
        35      Running         4266 ms
        37      Sleeping        4536 ms
        39      Sleeping        4786 ms
        42      Running         5087 ms
        44      Running         5387 ms