本範例示範在外部類別建構子中,透過迴圈建立多個內部執行緒類別實例並啟動,每個執行緒透過建構子參數區分身分,展現批量併發啟動的基本模式。
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(); // 關閉執行緒池
}
}
new Thread 無上限ThreadFactory + UncaughtExceptionHandler)new Thread 或內部類別模式足夠ExecutorService、ThreadPoolExecutor 等池化方案ScheduledExecutorService理解手動建立執行緒的基礎模式,是掌握執行緒池等進階機制的前提。