ThreadGroup

In this chapter you will learn:

  1. Listing all threads and threadgroups in the VM

Listing all threads and threadgroups in the VM

public class Main{
  private static void printThreadInfo(Thread t, String indent) {
    if (t == null)
      return;// ja  va  2s .  co m
    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 main(String[] args) {
    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, "");
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Java BlockingQueue with multiple threads
  2. BlockingQueue and Executors
  3. File searching with BlockingQueue
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor