查看JVM中的线程
--如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3890280.html "谢谢--
ThreadGroup(线程组)
1.一个线程的集合,也可包含其他线程组 2.线程组构成一棵树,除了初始化线程组外,每一个线程组都有一个父线程组 3.允许线程访问有关自己的线程组的信息,但不能访问其父线程组或其他线程组的信息 4.ThreadGroup类只能获得处于运行状态的线程
常用方法: activeCount() 返回线程组中活动线程的估计数 activeGroupCount() 返回线程组中活动线程组的估计数 enumerate(Thread[] list,boolean recurse) 把此线程组中所有活动线程复制到指定数组中 enumerate(ThreadGroup[] list,boolean recurse) 把此线程组中所有活动子组的引用复制到指定的数组中 enumerate(Thread[] list) 把此线程组中所有活动线程复制到指定数组中 enumerate(ThreadGroup[] list) 把此线程组中所有活动子组的引用复制到指定的数组中 getName() 返回此线程组的名称 getParent() 返回此线程组的父线程组
代码例子: package com.xhj.thread;
import java.util.ArrayList; import java.util.List;
/** * 查看JVM中的线程 获取线程名和子线程组 * * @author XIEHEJUN * */ public class CheckThreadJVM {
/** * 获取根线程组 * * @return */ public static ThreadGroup getRootThreadGroup() { ThreadGroup rootGroup = Thread.currentThread().getThreadGroup(); while (true) { if (rootGroup.getParent() != null) { rootGroup = rootGroup.getParent(); } else { break; } } return rootGroup; }
/** * 获取线程组中的线程名 * * @param group * @return */ public static List<String> getThreadsName(ThreadGroup group) { List<String> threadList = new ArrayList<String>(); Thread[] threads = new Thread[group.activeCount()]; int count = group.enumerate(threads, false); for (int i = 0; i < count; i++) { threadList.add(group.getName() + "线程组: " + threads[i].getName()); } return threadList; }
/** * 获取根数组下的子数组 * * @param group * @return */ public static List<String> getThreadGroup(ThreadGroup group) { List<String> threadList = getThreadsName(group); ThreadGroup[] threads = new ThreadGroup[group.activeGroupCount()]; int count = group.enumerate(threads, false); for (int i = 0; i < count; i++) { threadList.addAll(getThreadsName(threads[i])); } return threadList;
}
public static void main(String[] args) { for (String string : getThreadGroup(getRootThreadGroup())) { System.out.println(string); } }
}