123,690
社区成员
发帖
与我相关
我的任务
分享
题目:查看 JVM 中线程的名称及其所在组的名称
创建一个类:Question78
定义3个方法:
线程组:表示一个线程的集合。还有线程组是可以包含其他线程组的。
线程组构成一棵树,除了初始化的线程组外,每个线程组都有一个父线程组。
package question;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Question78
* @Description
* @Author keke
* @Time 2022/5/28 22:06
* @Version 1.0
*/
public class Question78 {
public static void main(String[] args) {
for (String threadGroup : getThreadGroups(getRootThreadGroups())) {
System.out.println(threadGroup);
}
}
private static ThreadGroup getRootThreadGroups(){
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
while (true){
if (rootGroup.getParent() != null){
rootGroup = rootGroup.getParent();
}else {
break;
}
}
return rootGroup;
}
public static List<String> getThreads(ThreadGroup group){
List<String> threadList = new ArrayList<>();
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;
}
public static List<String> getThreadGroups(ThreadGroup group){
List<String> threadList = getThreads(group);
ThreadGroup[] groups = new ThreadGroup[group.activeCount()];
for (int i = 0; i < group.enumerate(groups, false); i++) {
threadList.addAll(getThreads(groups[i]));
}
return threadList;
}
}