Listing All Running Threads - Java Thread

Java examples for Thread:Thread Operation

Description

Listing All Running Threads

Demo Code



public class Main {
  public static void main(String[] args) throws Exception {
    // Find the root thread group
    ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
    while (root.getParent() != null) {
      root = root.getParent();//  ww w  .  jav a2s  .  c o  m
    }
    // Visit each thread group
    visit(root, 0);
  }

  public static void visit(ThreadGroup group, int level) {
    // Get threads in `group'
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads * 2];
    numThreads = group.enumerate(threads, false);

    // Enumerate each thread in `group'
    for (int i = 0; i < numThreads; i++) {
      // Get thread
      Thread thread = threads[i];
    }

    // Get thread subgroups of `group'
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
    numGroups = group.enumerate(groups, false);

    // Recursively visit each subgroup
    for (int i = 0; i < numGroups; i++) {
      visit(groups[i], level + 1);
    }
  }
}

Related Tutorials