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

100 行 Java 程式碼建構執行緒池:wait/notify 機制實作詳解

     編輯:Java 相關知識

核心架構三類別

  • TestThreadPool:測試主程式,模擬客戶請求
  • ThreadPoolManager:池管理器,負責初始化與分派
  • SimpleThread:工作執行緒,實際處理任務

完整實作程式碼

SimpleThread.java (工作執行緒)

class SimpleThread extends Thread {
    private boolean running = false;
    private String task;
    
    SimpleThread(int id) {
        super("Worker-" + id);
        System.out.println(getName() + " 已啟動");
    }
    
    synchronized void assign(String task) {
        this.task = task;
        this.running = true;
        notify(); // 喚醒等待中的執行緒
    }
    
    synchronized boolean isIdle() { return !running; }
    
    public void run() {
        try {
            while (true) {
                synchronized (this) {
                    while (!running) wait(); // 閒置等待
                }
                // 處理任務
                System.out.println(getName() + " 處理: " + task + " ... 完成");
                Thread.sleep(5000); // 模擬耗時操作
                System.out.println(getName() + " 進入閒置");
                synchronized (this) { running = false; }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

ThreadPoolManager.java (管理器)

class ThreadPoolManager {
    private final List workers = new ArrayList<>();
    
    ThreadPoolManager(int size) {
        for (int i = 1; i <= size; i++) {
            SimpleThread t = new SimpleThread(i);
            workers.add(t);
            t.start();
        }
    }
    
    void process(String task) {
        for (SimpleThread t : workers) {
            if (t.isIdle()) {
                t.assign(task);
                return;
            }
        }
        System.out.println("執行緒池已滿,請稍後再試");
    }
}

TestThreadPool.java (測試)

public class TestThreadPool {
    public static void main(String[] args) throws IOException {
        ThreadPoolManager pool = new ThreadPoolManager(10);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        while ((input = br.readLine()) != null) {
            pool.process(input);
        }
    }
}

關鍵機制解析

  • wait/notify:執行緒在 wait() 釋放鎖進入等待集合,notify() 喚醒一個執行緒重新競爭鎖
  • synchronized 保護:wait/notify 必須在同步區塊內,否則拋出 IllegalMonitorStateException
  • 狀態旗標:running 區分閒置/忙碌,避免虛假喚醒
  • while 迴圈檢查:while (!running) wait() 防止虛假喚醒

生產級改進方向

  • 使用 BlockingQueue 替代手工分派
  • 採用 ThreadPoolExecutor 內建拒絕策略
  • 支援動態調整核心/最大執行緒數
  • 加入任務逾時、監控指標、優雅關閉
  • 使用 CompletableFuture 非阻塞組合
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved