介绍
线程组代表一组线程。另外,线程组还可以包括其他线程组。线程组形成一棵树,其中除初始线程组外的每个线程组都有一个父级。一个线程被允许访问有关其自己线程的信息组,但不能访问有关其线程组的父线程组或任何其他线程组的信息。
统一管理线程
线程组树的结构:
- JVM创建的system线程组是用来处理JVM的系统任务的线程组,例如对象的销毁等。
- system线程组的直接子线程组是main线程组,这个线程组至少包含一个main线程,用于执行main方法。
- main线程组的子线程组就是应用程序创建的线程组。
构造
java.lang.ThreadGroup
提供了两个构造函数:
Constructor | Description |
---|---|
ThreadGroup(String name) | 根据线程组名称创建线程组,其父线程组为创建线程组所在线程的父线程组(Thread.currentThread().getThreadGroup() ) |
ThreadGroup(ThreadGroup parent, String name) | 根据线程组名称创建线程组,其父线程组为指定的 |
源码解析
java.lang.ThreadGroup
内部数据存储 | 基数 | 扩容倍数 |
---|---|---|
Thread threads[] | 4 | 2 |
ThreadGroup groups[] | 4 | 2 |
再移除的时候会缩短数据容量,看代码
private void remove(Thread t) {
synchronized (this) {
if (destroyed) {
return;
}
for (int i = 0 ; i < nthreads ; i++) {
if (threads[i] == t) {
System.arraycopy(threads, i + 1, threads, i, --nthreads - i);
// Zap dangling reference to the dead thread so that
// the garbage collector will collect it.
threads[nthreads] = null;
break;
}
}
}
}