Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 多執行緒:為什麼需要執行緒池,以及如何實作

簡介

為了給並發開發提供更好的支援,Java 除了 Thread 類別與 Runnable 介面,還提供了執行緒池等管理工具,用來提升並發程式的效能。

無限制建立執行緒的代價

多執行緒確實能提高多核心處理器的運算能力與系統吞吐量,但不加限制地使用,效能不但不會提升,反而會下降。

new Thread().start() 這種寫法在簡單系統沒問題,但在真實生產環境中,某個瞬間可能有大量請求湧入,若為每個請求都建立一個執行緒,數量一多就會耗盡 CPU 與記憶體。原因有三:執行緒雖是輕量級工具,建立與銷毀仍需時間;每個執行緒本身要佔用堆疊記憶體空間,數量過大會導致 OutOfMemoryError;大量執行緒的回收會給 GC 帶來沉重壓力,延長停頓時間。

結論很明確:執行緒的使用必須控制在合理範圍,超過臨界點,它就會反過來拖垮整個系統。生產環境一定要管理。

執行緒池的核心概念

既然頻繁建立與銷毀会带来額外開銷,就需要一種復用機制。執行緒池的做法是:接到任務時先別急著建立執行緒,而是看看池中是否有閒置執行緒;有的話直接拿去用,沒有的話才建立新的。任務完成後也不銷毀,而是放回池中等待下次復用。

自行實作一個簡易執行緒池

public class ThreadPool {
    private static ThreadPool instance = null;
    private List<PThread> idleThreads; // 空閒執行緒佇列
    private int threadCounter;         // 已建立的執行緒總數
    private boolean isShutdown = false;

    public ThreadPool() {
        idleThreads = new Vector<PThread>(5);
        threadCounter = 0;
    }

    public synchronized int getCreatedThreadsCount() {
        return threadCounter;
    }

    public synchronized static ThreadPool getInstatce() {
        if (instance == null) {
            instance = new ThreadPool();
        }
        return instance;
    }

    /** 把執行緒重新放回池中 */
    public synchronized void repool(PThread repoolThread) {
        if (!isShutdown) {
            idleThreads.add(repoolThread);
        } else {
            repoolThread.shutdown();
        }
    }

    /** 停止池中所有執行緒 */
    public synchronized void shutdown() {
        isShutdown = true;
        for (int i = 0; i < idleThreads.size(); i++) {
            idleThreads.get(i).shutdown();
        }
    }

    /** 執行任務 */
    public synchronized void start(Runnable target) {
        PThread pthread = null;
        if (idleThreads.size() > 0) {          // 有閒置執行緒
            int index = idleThreads.size() - 1;
            pthread = idleThreads.get(index);
            idleThreads.remove(index);
            pthread.setTarget(target);
        } else {                                // 沒有閒置執行緒
            threadCounter++;
            PThread p = new PThread(instance, target, "PThread#" + threadCounter);
            p.start();
        }
    }
}

配套的工作執行緒,重點是「永不自行結束,一直等待新任務」:

public class PThread extends Thread {
    private ThreadPool pool;
    private Runnable target;
    private boolean isShutDown = false;
    private boolean isIdle = false;

    public PThread(ThreadPool pool, Runnable target, String name) {
        super(name);
        this.pool = pool;
        this.target = target;
    }

    @Override
    public void run() {
        while (!isShutDown) {
            isIdle = false;
            if (target != null) {
                target.run();
            }
            isIdle = true;
            pool.repool(this);
            synchronized (this) {
                wait();     // 閒置,等待任務到來
            }
            isIdle = false;
        }
    }

    public synchronized void setTarget(Runnable target) {
        this.target = target;
        notifyAll();        // 有任務了,叫醒它
    }

    public synchronized void shutdown() {
        isShutDown = true;
        notifyAll();
    }
}

測試:

public class TestClient {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        long begin = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            // new Thread(new MyThread("testnopoolThread" + i)).start();
            ThreadPool.getInstatce().start(new MyThread("testpoolThread" + i));
            // executor.execute(new MyThread("executorpoolThread" + i));
        }
        System.out.println(System.currentTimeMillis() - begin);
    }
}

這份實作有個明顯缺陷值得注意:idleThreads 用 Vector 雖然執行緒安全,但每次取用都要鎖,且池大小沒有上限,高壓下仍可能無限擴張。它適合當教學範例,不適合上生產。

Executor 框架

JDK 提供完整的 Executor 框架。ThreadPoolExecutor 是執行緒池實作,Executors 則扮演工廠角色:

  • newFixedThreadPool():固定數量,任務超出時進入佇列排隊。
  • newSingleThreadExecutor():只有一個執行緒,任務以先進先出順序執行。
  • newCachedThreadPool():依需求伸縮,優先復用閒置執行緒。
  • newSingleThreadScheduledExecutor():回傳 ScheduledExecutorService,可延遲或週期性執行。

若要自訂,直接建立 ThreadPoolExecutor,它的核心建構子參數決定了行為:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

其中 workQueue 的選擇影響最深:使用無界佇列(如 LinkedBlockingQueue 不帶容量)時,maximumPoolSize 實際上永遠不會生效;使用 SynchronousQueue 則會逼出最大執行緒數。另外,Executors 的幾個靜態工廠在阿里 Java 開發手冊中被列為「不建議使用」,原因正是它們可能建立無界佇列或無上限執行緒數,把 OOM 風險交給運氣。生產環境請直接自建 ThreadPoolExecutor 並明確設定 RejectedExecutionHandler。

Copyright © Linux教程網 All Rights Reserved