ThreadGroup类的常用方法
activeCount()——返回此线程组中活动线程的估计数
activeGroupCount()——返回此线程组中活动线程组的估计数
enumerate(Thread[] list,boolean recurse)——把此线程组中所有活动线程复制到指定数组中
enumerate(ThreadGroup[] list,boolean recurse)——把对此线程中的所有活动子组的引用复制到指定数组中
getName()——返回此线程组的名称
getParent()——返回此线程组的父线程组
/** * 获得根线程组 * @return */ private static ThreadGroup getRootThreadGroups(){ //获得当前线程组 ThreadGroup rootGroup =Thread.currentThread().getThreadGroup(); while(true){ //如果getParent()方法的返回值非空则不是根线程组 if(rootGroup.getParent()!=null){ //获得父线程组 rootGroup=rootGroup.getParent(); }else{ //如果到达根线程组则退出循环 break; } } //返回根线程组 return rootGroup; } /** * 获得给定线程组中所有线程名 * @param group * @return */ public static List<String> getThreads(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>getThreadGroups(ThreadGroup group){ //获得给定线程组中线程名 List<String> threadList=getThreads(group); //创建线程组数组 ThreadGroup[] groups=new ThreadGroup[group.activeGroupCount()]; //复制子线程组到线程组数据 int count=group.enumerate(groups,false); //遍历所有子线程组 for(int i=0;i<count;i++){ //利用getThreads()方法获得线程名列表 threadList.addAll(getThreads(groups[i])); } //返回所有线程名 return threadList; } public static void main(String[] args) throws InterruptedException { for(String string:getThreadGroups(getRootThreadGroups())){ //遍历输出列表中的字符串 System.out.println(string); } }
结果: