介紹
線程組代表一組線程。另外,線程組還可以包括其他線程組。線程組形成一棵樹,其中除初始線程組外的每個線程組都有一個父級。一個線程被允許訪問有關其自己線程的信息組,但不能訪問有關其線程組的父線程組或任何其他線程組的信息。
統一管理線程
線程組樹的結構:
- 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;
}
}
}
}