ThreadGroup 將相關執行緒組織成樹狀結構,支援批次操作(中斷、停止、列舉)、安全性檢查、未捕獲異常統一處理。雖然現代開發較少直接使用,但理解其機制有助於掌握 JVM 執行緒模型全貌。
public class myThreadgroup extends Thread {
public static int flag = 1;
ThreadGroup tgA;
ThreadGroup tgB;
public static void main(String[] args) {
myThreadgroup dt = new myThreadgroup();
dt.tgA = new ThreadGroup("A"); // 建立群組 A
dt.tgB = new ThreadGroup("B"); // 建立群組 B
// 群組 A:2 條執行緒,休眠 1000ms、2000ms
for (int i = 1; i < 3; i++)
new thread1(dt.tgA, i * 1000, "one" + i);
// 群組 B:2 條執行緒,休眠 1000ms
for (int i = 1; i < 3; i++)
new thread1(dt.tgB, 1000, "two" + i);
dt.start(); // 啟動主執行緒(控制器)
}
// 主執行緒:延遲後批次停止群組
public void run() {
try {
this.sleep(5000);
this.tgB.checkAccess(); // 安全性檢查
this.tgB.stop(); // 停止群組 B 所有執行緒
System.out.println("**************tgB stop!***********************");
this.sleep(1000);
this.tgA.checkAccess();
this.tgA.stop(); // 停止群組 A 所有執行緒
System.out.println("**************tgA stop!***********************");
} catch (SecurityException es) { System.out.println("**" + es); }
catch (Exception e) { System.out.println("::" + e); }
}
}
// 執行緒實作類別
class thread1 extends Thread {
int pauseTime;
String name;
public thread1(ThreadGroup g, int x, String n) {
super(g, n); // 指定所屬群組與名稱
pauseTime = x;
name = n;
start(); // 建構子即啟動
}
public void run() {
while (true) {
try {
System.out.print(name + "::::");
this.getThreadGroup().list(); // 列印群組資訊
Thread.sleep(pauseTime);
} catch (Exception e) { System.out.println(e); }
}
}
}
tgB.stop() 強制終止群組 B 所有執行緒tgA.stop() 終止群組 A 所有執行緒| 方法 | 功能 |
|---|---|
activeCount() | 估算群組中活躍執行緒數 |
enumerate(Thread[] list) | 將活躍執行緒複製到陣列 |
interrupt() | 中斷群組中所有執行緒 |
stop() | 已淘汰 強制停止所有執行緒(不安全) |
list() | 列印群組結構到標準輸出(除錯用) |
setUncaughtExceptionHandler() | 設定群組級未捕獲異常處理器 |
getParent() | 取得父群組 |
interrupt() + 旗標變數 + volatile 實現優雅停止public class GracefulThreadGroup {
static class Worker extends Thread {
private volatile boolean running = true;
public void run() {
while (running && !Thread.currentThread().isInterrupted()) {
// 工作邏輯
}
}
public void shutdown() { running = false; }
}
public static void main(String[] args) throws InterruptedException {
ThreadGroup group = new ThreadGroup("Workers");
Worker[] workers = new Worker[5];
for (int i = 0; i < 5; i++) {
workers[i] = new Worker();
workers[i].start();
}
Thread.sleep(2000);
// 優雅關閉
for (Worker w : workers) w.shutdown();
group.interrupt(); // 輔助中斷阻塞操作
}
}
Thread.getAllStackTraces() 更現代)checkAccess())ThreadGroup 是早期 Java 並發設計的產物,現代開發以 ExecutorService、CompletableFuture、ThreadFactory 替代,但理解其概念對排查生產環境執行緒問題仍有助益。