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

[JAVA100例] 第63例:線程組管理——ThreadGroup 批量控制線程

     編輯:Java 相關知識

本例演示使用 ThreadGroup 將線程分組管理:創建兩組線程(A 組間隔 1-2 秒輸出、B 組間隔 1 秒輸出),主線程延時後依次停止 B 組再停止 A 組。

核心代碼

public class myThreadgroup extends Thread {
  public static int flag = 1;
  ThreadGroup tgA, tgB;

  public static void main(String[] args) {
    myThreadgroup dt = new myThreadgroup();
    dt.tgA = new ThreadGroup("A");
    dt.tgB = new ThreadGroup("B");
    for (int i = 1; i < 3; i++) new thread1(dt.tgA, i * 1000, "one" + i);
    for (int i = 1; i < 3; i++) new thread1(dt.tgB, 1000, "two" + i);
    dt.start();  // 啟動主線程(繼承 Thread)
  }

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

ThreadGroup 核心功能

方法用途
new ThreadGroup(name)創建線程組
new Thread(group, name)將線程加入指定組
group.stop()停止組內所有線程(已棄用,不安全)
group.interrupt()中斷組內所有線程(推薦)
group.list()打印組結構與線程狀態(調試用)
group.activeCount()獲取活躍線程數
group.enumerate(Thread[])複製活躍線程到數組
checkAccess()檢查修改權限(安全管理器)

關鍵缺陷與現代替代

  • ThreadGroup.stop() 已棄用:同 Thread.stop(),強制釋放鎖導致數據損壞
  • ThreadGroup 設計缺陷多,Josh Bloch 稱其「失敗的實驗」
  • 現代替代:ExecutorService + ThreadFactory

現代線程組管理最佳實踐

// 1. 自定義 ThreadFactory 設置線程名稱前綴、守護屬性
ThreadFactory factory = new ThreadFactoryBuilder()
  .setNameFormat("OrderProcessor-%d")
  .setDaemon(true)
  .build();

// 2. 線程池隔離不同業務
ExecutorService orderPool = Executors.newFixedThreadPool(10, factory);
ExecutorService notifyPool = Executors.newCachedThreadPool(factory);

// 3. 批量關閉
orderPool.shutdown();
notifyPool.shutdown();
try {
  if (!orderPool.awaitTermination(60, TimeUnit.SECONDS)) orderPool.shutdownNow();
} catch (InterruptedException e) { orderPool.shutdownNow(); }

JDK 21+ 結構化併發

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
  var orderTask = scope.fork(() -> processOrder());
  var notifyTask = scope.fork(() -> sendNotification());
  scope.join();           // 等待所有完成
  scope.throwIfFailed();  // 任一失敗則取消其餘
}

自動處理錯誤傳播、取消傳播、生命週期綁定,徹底替代 ThreadGroup。

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