Listing All Threads


public static void listThreads() {    ThreadGroup root = Thread.currentThread()       .getThreadGroup().getParent();    while (root.getParent() != null) {       root = root.getParent();    }     visitGroup(root, 0); } public static void visitGroup(ThreadGroup group, int level) {    int numThreads = group.activeCount();    Thread[] threads = new Thread[numThreads];    group.enumerate(threads, false);    for (int i=0; i<numThreads; i++) {       Thread thread = threads[i];       printThreadInfo(thread);    }    int numGroups = group.activeGroupCount();    ThreadGroup[] groups = new ThreadGroup[numGroups];    numGroups = group.enumerate(groups, false);    for (int i=0; i<numGroups; i++) {       visitGroup(groups[i], level+1);    } } private static void printThreadInfo(Thread t) {    System.out.println("Thread: " + t.getName( ) +                " Priority: " + t.getPriority( ) +                (t.isDaemon( )?" Daemon":"") +                (t.isAlive( )?"":" Not Alive")); }



In this phrase we list all running threads. All threads exist in a thread group, and each thread group can contain threads and other thread groups. The THReadGroup class allows you to group threads and call methods on the THReadGroup class that will affect all threads in the thread group. THReadGroups can also contain child THReadGroups. THReadGroups organize all threads into a hierarchy.

In this phrase we iterate through all thread groups to print information about each thread. We start by finding the root thread group. We then use the visitGroup() method to recursively visit each thread group that exists under the root group. Within the visitGroup() method, we first enumerate all the threads contained in that group. We call the printThreadInfo() method, also contained in the phrase, to print the name, priority, daemon status, and alive status of each thread. After having iterated through all the threads in the current group, we enumerate all the groups contained within the current group and make a recursive call to the visitGroup() method for each group. This recursive method calling continues until all the groups and all the threads have been enumerated and information about each thread has been printed.

Thread groups are commonly used to group threads that are related or similar in some way, such as who created them, what function they perform, or when they should be started and stopped.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net