Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class Main {
    private static ThreadGroup ROOT = null;

    public static Thread[] getAllThreads() {

        final ThreadGroup root = getRootThreadGroup();
        final ThreadMXBean thbean = ManagementFactory.getThreadMXBean();

        int nAlloc = thbean.getThreadCount();
        int n = 0;
        Thread[] threads;

        do {
            nAlloc *= 2;
            threads = new Thread[nAlloc];
            n = root.enumerate(threads, true);
        } while (n == nAlloc);

        return java.util.Arrays.copyOf(threads, n);
    }

    private static ThreadGroup getRootThreadGroup() {

        if (ROOT == null) {
            ThreadGroup current = Thread.currentThread().getThreadGroup();
            ThreadGroup parent;
            while ((parent = current.getParent()) != null)
                current = parent;
            ROOT = current;
        }

        return ROOT;
    }
}