enumerate方法用来将ThreadGroup线程组中的active线程全部复制到Thread类型的数组中,并且返回数组中元素个数,即线程组中active线程数量。有以下两种调用方法:
public int enumerate(Thread[] list) {
this.checkAccess();
return this.enumerate((Thread[])list, 0, true);
}
public int enumerate(Thread[] list, boolean recurse) {
this.checkAccess();
return this.enumerate((Thread[])list, 0, recurse);
}
上述两种方法都调用了ThreadGroup的私有方法enumerate:
private int enumerate(Thread[] list, int n, boolean recurse) {
int ngroupsSnapshot = 0;
ThreadGroup[] groupsSnapshot = null;
synchronized(this) {
if (this.destroyed) {
return 0;
}
int nt = this.nthreads;
if (nt > list.length - n) {
nt = list.length - n;
}
for(int i = 0; i < nt; ++i) {
if (this.threads[i].isAlive()) {
list[n++] = this.threads[i];
}
}
if (recurse) {
ngroupsSnapshot = this.ngroups;
if (this.groups != null) {
groupsSnapshot = (ThreadGroup[])Arrays.copyOf(this.groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
}
if (recurse) {
for(int i = 0; i < ngroupsSnapshot; ++i) {
n = groupsSnapshot[i].enumerate(list, n, true);
}
}
return n;
}
从上述代码可以看出,enumerate(Thread[] list)方法实际上就是enumerate(Thread[] list,true)的方法。那么形参recurse设置为true或者false到底有什么区别呢?事实上,true的情况是将所有子group中的active线程都递归到Thread数组中,而false的情况则是将ThreadGroup(父线程组)中的active线程全部复制到Thread数组中。我们通常称true的情况是递归方法,而false的方法是非递归方法。因为看一下私有方法enumerate的代码实现会发现二者就差了递归调用的方法。下面是具体的代码实现:
import java.util.concurrent.TimeUnit;
public class ThreadGroupEnumerateThreads {
public static void main(String[] args) throws InterruptedException {
ThreadGroup myGroup=new ThreadGroup("MyGroup");
Thread thread=new Thread(myGroup,()->
{
while(true){
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
}
},"MyThread");
thread.start();
TimeUnit.MILLISECONDS.sleep(2);
ThreadGroup mainGroup=Thread.currentThread().getThreadGroup();
Thread[] list=new Thread[mainGroup.activeCount()];
int recurseSize=mainGroup.enumerate(list);
System.out.println(recurseSize);
recurseSize=mainGroup.enumerate(list,false);
System.out.println(recurseSize);
}
}
运行结果分别输出3和2。
关系图如下所示: