Print all running threads - Java java.lang

Java examples for java.lang:Thread

Description

Print all running threads

Demo Code


//package com.java2s;
import java.io.PrintWriter;
import java.io.StringWriter;

public class Main {
    public static void main(String[] argv) throws Exception {
        printRunningThreads();/*w ww .j  a v a 2s . c  om*/
    }

    /**
     * Print all running threads
     */
    public static void printRunningThreads() {
        // Get the thread listing as a string using a StringWriter stream
        StringWriter stringWriter = new StringWriter();
        PrintWriter out = new PrintWriter(stringWriter);
        listAllThreads(out);
        out.close();
        String threadListing = stringWriter.toString();
        System.out.println(threadListing);
    }

    /**
     * Find the root thread group and list it recursively
     */
    private static void listAllThreads(PrintWriter out) {
        ThreadGroup root = getRootThreadGroup();
        printGroupInfo(out, root, "");
    }

    /**
     * Get root thread group
     *
     * @return root thread group
     */
    private static ThreadGroup getRootThreadGroup() {
        ThreadGroup root = Thread.currentThread().getThreadGroup();
        ThreadGroup parent = root.getParent();
        while (parent != null) {
            root = parent;
            parent = parent.getParent();
        }
        return root;
    }

    /**
     * Display info about a thread group and its threads and groups
     */
    private static void printGroupInfo(PrintWriter out, ThreadGroup g,
            String indent) {
        if (g == null) {
            return;
        }
        int num_threads = g.activeCount();
        int num_groups = g.activeGroupCount();
        Thread[] threads = new Thread[num_threads];
        ThreadGroup[] groups = new ThreadGroup[num_groups];

        g.enumerate(threads, false);
        g.enumerate(groups, false);

        out.println(indent + "Thread Group: " + g.getName()
                + "  Max Priority: " + g.getMaxPriority()
                + (g.isDaemon() ? " Daemon" : ""));

        for (int i = 0; i < num_threads; i++) {
            printThreadInfo(out, threads[i], indent + "    ");
        }
        for (int i = 0; i < num_groups; i++) {
            printGroupInfo(out, groups[i], indent + "    ");
        }
    }

    /**
     * Display information about a thread.
     */
    private static void printThreadInfo(PrintWriter 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"));
    }
}

Related Tutorials