線程池用於限制應用程序中同時運行的線程數量。每啟動一個新線程都伴隨性能開銷(棧內存分配等)。將並發任務提交給線程池,由空閒線程從阻塞隊列中取出任務執行,可顯著提升性能與資源利用率。常見於多線程服務器,每個網絡連接封裝為任務交由線程池處理。
Java 5 在 java.util.concurrent 包提供內置線程池實現,開發者無需自行構建。核心接口為 ExecutorService,常用工廠方法:
Executors.newFixedThreadPool(int n):固定大小線程池。Executors.newCachedThreadPool():可緩存線程池,按需創建。Executors.newSingleThreadExecutor():單線程池,保證順序執行。Executors.newScheduledThreadPool(int n):定時/周期性任務調度。以下簡化示例展示線程池核心結構:
public class ThreadPool {
private BlockingQueue<Runnable> taskQueue;
private List<PoolThread> threads;
private boolean isStopped = false;
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
taskQueue = new BlockingQueue(maxNoOfTasks);
for (int i = 0; i < noOfThreads; i++) {
threads.add(new PoolThread(taskQueue));
}
for (PoolThread thread : threads) {
thread.start();
}
}
public synchronized void execute(Runnable task) {
if (isStopped) throw new IllegalStateException("ThreadPool is stopped");
taskQueue.enqueue(task);
}
public synchronized void stop() {
isStopped = true;
for (PoolThread thread : threads) {
thread.stop();
}
}
}
PoolThread 內部循環從隊列取任務執行,stop() 通過中斷機制安全終止線程。
stop() 設置標誌位並中斷等待中的線程,避免數據不一致。execute() 在池關閉後拋出 IllegalStateException。Executors 工廠或 ThreadPoolExecutor 自定義參數(核心/最大線程數、存活時間、隊列類型、拒絕策略)。shutdown() 或 shutdownNow(),並配合 awaitTermination() 等待任務完成。