核心組件:LinkedList<Runnable> workQueue + 固定數量 WorkThread。execute() 入隊 + notify();getTask() 阻塞取任務;close() 清隊列+中斷線程;join() 等待任務執行完再關閉。
public class MyThreadPool extends ThreadGroup {
private final LinkedList<Runnable> workQueue = new LinkedList<>();
private boolean isClosed = false;
public MyThreadPool(int poolSize) { ... for(i) new WorkThread().start(); }
public synchronized void execute(Runnable task) { ... workQueue.add(task); notify(); }
protected synchronized Runnable getTask() throws InterruptedException { ... wait(); return workQueue.removeFirst(); }
public synchronized void close() { isClosed=true; workQueue.clear(); interrupt(); }
public void join() { ... enumerate threads; each.join(); }
class WorkThread extends Thread {
public void run() { while(!isInterrupted()) { Runnable t = getTask(); if(t!=null) t.run(); else break; } }
}
}
ExecutorService ← ThreadPoolExecutor ← ScheduledThreadPoolExecutor。核心參數:corePoolSize、maximumPoolSize、keepAliveTime、workQueue、ThreadFactory、RejectedExecutionHandler。常用工廠方法:Executors.newFixedThreadPool()、newCachedThreadPool()、newSingleThreadExecutor()、newScheduledThreadPool()。
<bean id="executorService" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="${threadpool.corePoolSize}"/>
<property name="maxPoolSize" value="${threadpool.maxPoolSize}"/>
<property name="queueCapacity" value="${threadpool.queueCapacity}"/>
<property name="keepAliveSeconds" value="${threadpool.keepAliveSeconds}"/>
</bean>
注入 Service 中:@Autowired ExecutorService executor; 即可 executor.execute(() -> ...)。
| 風險 | 成因 | 對策 |
|---|---|---|
| 死鎖 | 線程互相等待鎖/任務等待子任務但池已滿 | 避免任務內同步調用同池任務;拆分專用池 |
| 資源耗盡 | 核心數過大、隊列無界 | 有界隊列 + 拒絕策略 + 監控指標 |
| 併發錯誤 | wait/notify 使用不當丟失喚醒 | 優先用 JDK 成熟實現,少寫鎖代碼 |
| 線程洩漏 | 任務拋出未捕獲異常導致工作線程死亡 | 任務包裹 try-catch + Thread.setDefaultUncaughtExceptionHandler |
| 任務過載 | 隊列堆積大量耗時任務 | 異步拒絕、降級、剝離 IO 密集型任務至專用池 |
原則:有界、隔離、可觀測、優雅關閉。