PHP笔记网

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

作者:Albert.Wen  添加时间:2019-07-29 18:00:33  修改时间:2024-11-08 15:49:44  分类:07.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;
    }
}