// This example is from the book _Java in a Nutshell_ by David Flanagan. // Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates. // You may study, use, modify, and distribute this example for any purpose. // This example is provided WITHOUT WARRANTY either expressed or implied. import java.io.*; public class ThreadLister { // Display info about a thread. private static void printThreadInfo(PrintStream out, Thread t, String indent) { if ( t == null ) return; out.println(indent + "+--> Thread: " + t.getName() + " Priority: " + t.getPriority() + (t.isDaemon()?" Daemon":"") + (t.isAlive()?"":" Not Alive")); } // Display info about a thread group and its threads and groups private static void listGroup(PrintStream out, ThreadGroup g, String indent) { if (g == null) return; int nrThreads = g.activeCount(); int nrGroups = g.activeGroupCount(); Thread[] threads = new Thread[nrThreads]; ThreadGroup[] groups = new ThreadGroup[nrGroups]; g.enumerate(threads, false); g.enumerate(groups, false); out.println("\n" + indent + " Thread Group: " + g.getName() + " Max Priority: " + g.getMaxPriority() + (g.isDaemon()?" Daemon":"")); for(int i = 0; i < nrThreads; i++) printThreadInfo(out, threads[i], indent + " "); for(int i = 0; i < nrGroups; i++) listGroup(out, groups[i], indent + " "); } // Find the root thread group and list it recursively public static void listAllThreads(PrintStream out) { ThreadGroup currentThreadGroup; ThreadGroup rootThreadGroup; ThreadGroup parent; // Get the current thread group currentThreadGroup = Thread.currentThread().getThreadGroup(); // Now go find the root thread group rootThreadGroup = currentThreadGroup; try { while( true ) { rootThreadGroup.checkAccess(); parent = rootThreadGroup.getParent(); if( parent == null ) break; rootThreadGroup = parent; } } catch( SecurityException e ) { ; } // And list it, recursively listGroup(out, rootThreadGroup, ""); } public static void main(String[] args) { ThreadLister.listAllThreads(System.out); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }