Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    public static String getThreadTree() {
        ThreadGroup root = Thread.currentThread().getThreadGroup();
        while (root.getParent() != null) {
            root = root.getParent();
        }
        StringBuffer buffer = new StringBuffer();

        buffer.append(root.toString()).append("\r");
        visit(root, 1, buffer);
        return buffer.toString();
    }

    public static void visit(ThreadGroup group, int level, StringBuffer buffer) {
        int numThreads = group.activeCount();
        Thread[] threads = new Thread[numThreads * 2];
        numThreads = group.enumerate(threads, false);
        for (int i = 0; i < numThreads; i++) {
            Thread t = threads[i];
            for (int j = 0; j < level; j++) {
                buffer.append("  ");
            }
            buffer.append(t.toString()).append("\r");
        }

        int numGroups = group.activeGroupCount();
        ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
        numGroups = group.enumerate(groups, false);
        for (int i = 0; i < numGroups; i++) {
            for (int j = 0; j < level; j++) {
                buffer.append("  ");
            }
            buffer.append(groups[i].toString()).append("\r");
            visit(groups[i], level + 1, buffer);
        }
    }
}