不灭的焱

革命尚未成功,同志仍须努力

作者:php-note.com  发布于:2019-08-04 00:08  分类:Java  编辑
package com.jianbao.helper.thread;

/**
 * 线程 助手类
 */
public class ThreadHelper {
    /**
     * 获取JVM中的所有线程
     *
     * @return 线程对象数组
     */
    public static Thread[] getAllThreads() {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;

        // 遍历线程组树,获取根线程组
        while (group != null) {
            topGroup = group;
            group = group.getParent();
        }

        // 激活的线程数加倍
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];

        // 获取根线程组的所有线程
        int actualSize = topGroup.enumerate(slackList);

        // copy into a list that is the exact size
        Thread[] list = new Thread[actualSize];
        System.arraycopy(slackList, 0, list, 0, actualSize);

        return list;
    }

    /**
     * 获取主线程
     *
     * @return 进程的主线程
     */
    public static Thread getMainThread() {
        for (Thread thread : getAllThreads()) {
            if (thread.getId() == 1) {
                return thread;
            }
        }

        return null;
    }
}