Listing all threads and threadgroups in the VM. : Utilities « Threads « Java






Listing all threads and threadgroups in the VM.

Listing all threads and threadgroups in the VM.
  
public class ThreadLister {
  private static void printThreadInfo(Thread t, String indent) {
    if (t == null)
      return;
    System.out.println(indent + "Thread: " + t.getName() + "  Priority: "
        + t.getPriority() + (t.isDaemon() ? " Daemon" : "")
        + (t.isAlive() ? "" : " Not Alive"));
  }

  /** Display info about a thread group */
  private static void printGroupInfo(ThreadGroup g, String indent) {
    if (g == null)
      return;
    int numThreads = g.activeCount();
    int numGroups = g.activeGroupCount();
    Thread[] threads = new Thread[numThreads];
    ThreadGroup[] groups = new ThreadGroup[numGroups];

    g.enumerate(threads, false);
    g.enumerate(groups, false);

    System.out.println(indent + "Thread Group: " + g.getName()
        + "  Max Priority: " + g.getMaxPriority()
        + (g.isDaemon() ? " Daemon" : ""));

    for (int i = 0; i < numThreads; i++)
      printThreadInfo(threads[i], indent + "    ");
    for (int i = 0; i < numGroups; i++)
      printGroupInfo(groups[i], indent + "    ");
  }

  /** Find the root thread group and list it recursively */
  public static void listAllThreads() {
    ThreadGroup currentThreadGroup;
    ThreadGroup rootThreadGroup;
    ThreadGroup parent;

    // Get the current thread group
    currentThreadGroup = Thread.currentThread().getThreadGroup();

    // Now go find the root thread group
    rootThreadGroup = currentThreadGroup;
    parent = rootThreadGroup.getParent();
    while (parent != null) {
      rootThreadGroup = parent;
      parent = parent.getParent();
    }

    printGroupInfo(rootThreadGroup, "");
  }

  public static void main(String[] args) {
    ThreadLister.listAllThreads();
  }
}

           
         
    
  








Related examples in the same category

1.View current Threads in a table View current Threads in a table
2.Exception call backException call back
3.Early returnEarly return
4.Transition DetectorTransition Detector
5.Busy Flag
6.Sleep utilities
7.Thread-based logging utility
8.Return a new instance of the given class. Checks the ThreadContext classloader first, then uses the System classloader.
9.Finds a resource with the given name.