JavaRanch Home    
This page:         last edited 25 February 2011         What's Changed?         Edit

Thread Lister   

This class lists all the currently active threads in a JVM. Note how the number of JVM-internal threads increases once GUI objects are used. If the code is part of a server application (like a web app), there will be even more threads.

public class ThreadLister {

    public static void main (String[] args)

        new javax.swing.JFrame();


    private static void listThreads()
        // Get the top level thread group
        ThreadGroup adam = getAdam(Thread.currentThread().getThreadGroup());

        // Get all of the active threads in the system
        Thread list[] = new Thread[adam.activeCount()];
        int numThreads = adam.enumerate(list);

        // Display all of the active threads in the system
        for (Thread th : list) {
            // a thread object can be null because the thread may
            // have terminated since we enumerated all threads
            if (th == null)
            System.out.println("group:" + th.getThreadGroup().getName()
                    + ", thread:" + th.getName()
                    + ", priority:" + th.getPriority()
                    + ", daemon:" + (th.isDaemon() ? "Yes" : "No")
                    + ", alive:" + (th.isAlive() ? "Yes" : "No"));

    // Recursively calls itself to find the top level thread group
    private static ThreadGroup getAdam (ThreadGroup tg)
        ThreadGroup parent = tg.getParent();
        if (parent == null)
            return tg;

        return getAdam(parent);

CodeBarn CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton