首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 執行緒群組管理:ThreadGroup 批次控制實戰

     編輯:Java 程式設計入門

ThreadGroup:執行緒的集中管理器

ThreadGroup 將相關執行緒組織成樹狀結構,支援批次操作(中斷、停止、列舉)、安全性檢查、未捕獲異常統一處理。雖然現代開發較少直接使用,但理解其機制有助於掌握 JVM 執行緒模型全貌。

完整程式碼:myThreadgroup.java + thread1.java

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); }
        }
    }
}

執行流程示意

  1. 主程式建立群組 A、B,各啟動 2 條執行緒(共 4 條子執行緒)
  2. 主執行緒(myThreadgroup 實例)啟動,休眠 5 秒觀察子執行緒運作
  3. 呼叫 tgB.stop() 強制終止群組 B 所有執行緒
  4. 休眠 1 秒後呼叫 tgA.stop() 終止群組 A 所有執行緒
  5. 程式結束

ThreadGroup 核心方法速查

方法功能
activeCount()估算群組中活躍執行緒數
enumerate(Thread[] list)將活躍執行緒複製到陣列
interrupt()中斷群組中所有執行緒
stop()已淘汰 強制停止所有執行緒(不安全)
list()列印群組結構到標準輸出(除錯用)
setUncaughtExceptionHandler()設定群組級未捕獲異常處理器
getParent()取得父群組

⚠️ 關鍵警示:stop()、suspend()、resume() 已淘汰

  • stop():強制釋放鎖,可能導致資料不一致、物件損壞
  • suspend()/resume():易造成死結
  • 現代替代方案:使用 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(); // 輔助中斷阻塞操作
    }
}

適用場景

  • 框架/容器層級的執行緒管理(如 Tomcat、Jetty 內部)
  • 測試/除錯階段快速檢視執行緒結構(Thread.getAllStackTraces() 更現代)
  • 安全性敏感環境的權限隔離(checkAccess())

ThreadGroup 是早期 Java 並發設計的產物,現代開發以 ExecutorService、CompletableFuture、ThreadFactory 替代,但理解其概念對排查生產環境執行緒問題仍有助益。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved