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

Java 多執行緒建構模式:內部類別實作批量啟動

     編輯:Java 程式設計入門

使用內部類別批量建立執行緒

本範例示範在外部類別建構子中,透過迴圈建立多個內部執行緒類別實例並啟動,每個執行緒透過建構子參數區分身分,展現批量併發啟動的基本模式。

完整程式碼:multiThread.java

public class multiThread {

    public static void main(String[] args) {
        new multiThread(); // 建構子內啟動所有執行緒
    }

    multiThread() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Creating thread " + i);
            innThread mt = new innThread(i);
            mt.start(); // 啟動第 i 條執行緒
        }
    }

    // 內部類別:繼承 Thread,以建構子參數區分身分
    class innThread extends Thread {
        int count;

        innThread(int i) {
            count = i;
        }

        public void run() {
            System.out.println("now " + count + " thread is beginning.....");
            try {
                sleep(10 - count); // 不同執行緒休眠不同時長
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println("\n" + count + " thread is end!");
        }
    }
}

執行結果示意(順序不定,視排程而定)

Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
now 0 thread is beginning.....
now 1 thread is beginning.....
now 2 thread is beginning.....
now 3 thread is beginning.....
now 4 thread is beginning.....
4 thread is end!
3 thread is end!
2 thread is end!
1 thread is end!
0 thread is end!

設計模式分析

模式要素本範例實作優點注意事項
執行緒建立外部類別建構子迴圈集中管理、易於批量控制大量建立時考慮執行緒池
參數傳遞內部類別建構子參數型別安全、編譯期檢查避免捕獲變動區域變數
身分識別count 欄位簡單直觀生產環境建議用有意義的業務 ID
生命週期start() 後各自獨立並發執行主執行緒不等待(若需等待用 join())

改進版:使用執行緒池(現代最佳實務)

import java.util.concurrent.*;

public class ModernMultiThread {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int id = i;
            executor.submit(() -> {
                System.out.println("Task " + id + " starting");
                try { Thread.sleep(10 - id); } catch (Exception ignored) {}
                System.out.println("Task " + id + " finished");
            });
        }
        executor.shutdown(); // 關閉執行緒池
    }
}

關鍵差異比較

  • 資源控制:執行緒池限制最大並發數,防止 OOM;手動 new Thread 無上限
  • 重用機制:池化重用執行緒,降低建立/銷毀開銷
  • 異常處理執行緒池可統一處理未捕獲異常(ThreadFactory + UncaughtExceptionHandler)
  • 監控指標:池提供隊列長度、活躍執行緒數等監控資料

適用場景建議

  • 教學/原型/簡單任務:手動 new Thread 或內部類別模式足夠
  • 生產/高併發/長期運行:務必使用 ExecutorService、ThreadPoolExecutor 等池化方案
  • 定時/週期任務:使用 ScheduledExecutorService

理解手動建立執行緒的基礎模式,是掌握執行緒池等進階機制的前提。

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