1.ThreadGroup 与 Thread
在Java程序中, 默认情况下, 新的线程都会被加入到main线程所在的group中, main线程的group名字同线程名。如同线程存在父子关系一样, Thread Group同样也存在父子关系。图6-1就很好地说明了父子thread、父子thread Group以及thread和group之间的层次关系
2.创建ThreadGroup
创建Thread Group的语法如下:
public Thread Group(String name)
public Thread Group(Thread Group parent, String name)
创建Thread Group的语法非常简单, 可通过上面某个构造函数来创建, 第一个构造函数为Thread Group赋予了名字, 但是该Thread Group的父Thread Group是创建它的线程所在的Thread Group; 第二个Thread Group的构造函数赋予group名字的同时又显式地指定了父Group。
public class TestThreadGroup {
public static void main(String[] args) {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
ThreadGroup group1 = new ThreadGroup("group1");
System.out.println(group1.getParent() == currentGroup);
ThreadGroup group2 = new ThreadGroup(group1, "Group2");
System.out.println(group2.getParent() == group1);
}
}
3.复制Thread数组和ThreadGroup数组
3,1复制Thread数组
public int enumerate(Thread[] list);
public int enumerate(Thread[] list, boolean recurse);
上述两个方法, 会将Thread Group中的active线程全部复制到Thread数组中, 其中recurse参数如果为true, 则该方法会将所有子group中的active线程都递归到Thread数组中, enumerate(Thread[] list) 实际上等价于enumerate(Thread[] true) , 上面两个方法都调用了Thread Group的私有方法enumerate:
private int enumerate(Thread list[], int n, boolean recurse) {
int ngroupsSnapshot = 0;
ThreadGroup[] groupsSnapshot = null;
synchronized (this) {
if (destroyed) {
return 0;
}
int nt = nthreads;
if (nt > list.length - n) {
nt = list.length - n;
}
for (int i = 0; i < nt; i++) {
if (threads[i].isAlive()) {
list[n++] = threads[i];
}