有时确定线程属于哪个线程组非常有用,ThreadGroup类包含用于创建及操纵线程组的方法。这样,甚至可以中断一个组中的所有线程。 activeCount方法报告组内活动线程及个数。enumerate将线和中活动的子线程复制到一个ThreadGroup引用数组中,其中一个方法使你能够递归地获得子线程组中所有活动线程组的copy。这里一个程序范例可以得到JVM启动后到底启动了哪些线程,他们的优先级是多少:
public class AllThread {
public static Thread[] getAllThread() {
ThreadGroup root = Thread.currentThread().getThreadGroup();
ThreadGroup ttg = root;
while ((ttg = ttg.getParent()) != null) root = ttg;
Thread[] tlist = new Thread[(int)(root.activeCount() * 1.2)];
return java.util.Arrays.copyOf(tlist, root.enumerate(tlist, true));
}
public static void main(String[] args) {
Thread[] ts = getAllThread();
for (Thread t : ts) {
System.out.println(t.getId() + ": " + t.getName() + " " + t.getPriority()); }
}