從零實現一個生產級線程池,深度理解「任務隊列 + 工作線程 + 鎖協作」核心架構。
LinkedList 緩衝 Runnable 任務getTask() → run(),池大小固定synchronized + wait/notify 實現生產者-消費者execute()、closePool()、waitFinish()public class ThreadPool extends ThreadGroup {
private boolean isClosed = false;
private LinkedList workQueue;
private static int threadPoolID = 1;
public ThreadPool(int poolSize) {
super(threadPoolID + "");
setDaemon(true);
workQueue = new LinkedList();
for (int i = 0; i < poolSize; i++) new WorkThread(i).start();
}
public synchronized void execute(Runnable task) {
if (isClosed) throw new IllegalStateException();
if (task != null) { workQueue.add(task); notify(); }
}
private synchronized Runnable getTask(int threadId) throws InterruptedException {
while (workQueue.size() == 0) {
if (isClosed) return null;
System.out.println("工作線程" + threadId + "等待任務...");
wait();
}
System.out.println("工作線程" + threadId + "開始執行任務...");
return (Runnable) workQueue.removeFirst();
}
public synchronized void closePool() {
if (!isClosed) {
waitFinish();
isClosed = true;
workQueue.clear();
interrupt(); // 繼承自 ThreadGroup,批量中斷
}
}
private class WorkThread extends Thread {
private int id;
public WorkThread(int id) { super(ThreadPool.this, id + ""); this.id = id; }
public void run() {
while (!isInterrupted()) {
Runnable task = null;
try { task = getTask(id); }
catch (InterruptedException ex) { ex.printStackTrace(); }
if (task == null) return;
try { task.run(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
}
}
ThreadPool pool = new ThreadPool(3); Thread.sleep(500); // 待線程啟動 for (int i = 0; i <= 5; i++) pool.execute(createTask(i)); pool.waitFinish(); pool.closePool();
工作線程0等待任務... 工作線程1等待任務... 工作線程2等待任務... 工作線程0開始執行任務... Hello world 工作線程0等待任務... 工作線程1開始執行任務... Hello world 工作線程1等待任務... 工作線程2開始執行任務... Hello world 工作線程2等待任務... 工作線程0開始執行任務... Hello world 工作線程0等待任務... 工作線程1開始執行任務... Hello world 工作線程1等待任務... 工作線程2開始執行任務... Hello world 工作線程2等待任務...
ThreadGroup 獲取線程管理能力wait/notify 實現無鎖空閒等待,CPU 友好waitFinish() 通過 join() 確保任務執行完畢再關閉