Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Java / Android 執行緒池完全解析

編輯:Android 程式設計入門

一、執行緒池是什麼、好在哪

想像一個快遞站:包裹(任務)陸續送來,站裡有固定數量的快遞員(執行緒),有人有空就派一件,忙不完就先堆在暫存區(佇列)。執行緒池就是這個模式。

它解決了直接 new Thread() 的三個痛點:

  1. 重用既有執行緒,省下反覆建立與銷毀的資源開銷。
  2. 能控制最大並發數,避免幾百個執行緒互搶 CPU 與記憶體而集體卡死。
  3. 便於統一管理,還能額外提供定時執行、固定週期重複執行等能力。

具體實作類別是 ThreadPoolExecutor,其最上層介面是 Executor。

二、七個建構參數

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
        TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler);
}
  1. corePoolSize:核心執行緒數。預設情況下核心執行緒會一直存活,即使閒置也不回收。若把 allowCoreThreadTimeOut 設為 true,核心執行緒也會套用第三個參數的超時策略,逾時即終結。
  2. maximumPoolSize:允許的最大執行緒數。活躍執行緒數達到此值後,新任務只能進佇列排隊,佇列滿了就依拒絕策略處理。
  3. keepAliveTime:非核心執行緒的閒置存活上限,超過就被回收。
  4. unit:keepAliveTime 的時間單位,列舉型別,常用 MILLISECONDS、SECONDS。
  5. workQueue:任務佇列。呼叫 execute() 送進來的 Runnable 先存在這裡。
  6. threadFactory:執行緒工廠,負責實際生出新的 Thread。
  7. (完整建構子還有第七個參數 RejectedExecutionHandler,決定任務被拒絕時怎麼辦。)

任務調度規則

  1. 執行緒數還沒到 corePoolSize,就直接開一條核心執行緒來跑。
  2. 核心執行緒已滿,任務塞進 workQueue 排隊。
  3. 佇列也滿了,才會開非核心執行緒來執行。
  4. 執行緒總數已達 maximumPoolSize 且佇列已滿,依拒絕策略處理這個任務。

關鍵順序很多人會記錯:先擴充佇列,再擴充執行緒。這也是為什麼使用無界佇列(如 LinkedBlockingQueue 不給容量)時,maximumPoolSize 實際上永遠用不到。

三、類別結構:一個抽象工廠模式

Executor 與 Executors 的差別

名字只差一個 s,角色完全不同。

Executor 是介面,只有一個方法:

public interface Executor {
    void execute(Runnable command);
}

Executors 則是工廠方法類別,不繼承任何父類,專門負責生產各種執行緒池物件,例如 FixedThreadPool、SingleThreadExecutor、ScheduledThreadPool。這些產品以及自訂的 ThreadPoolExecutor 都實作了 ExecutorService 介面,而 ExecutorService 又繼承自 Executor。

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
    return new FinalizableDelegatedExecutorService(
            new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(), threadFactory));
}

看這段原始碼就很清楚:所謂的「單執行緒池」,本質上就是 corePoolSize = maximumPoolSize = 1 的 ThreadPoolExecutor,外層再包一個委派類別,防止有人把它向下轉型後改參數。

ThreadFactory 也是面向介面

public interface ThreadFactory {
    Thread newThread(Runnable r);
}

與 Executor 同樣體現了面向介面編程。Executors 提供的兩個現成實作:

public static ThreadFactory defaultThreadFactory() {
    return new DefaultThreadFactory();
}
public static ThreadFactory privilegedThreadFactory() {
    return new PrivilegedThreadFactory();
}

DefaultThreadFactory 的實作值得參考,想自訂命名規則、優先權、是否守護執行緒,照著改就行:

static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

順帶一提,自訂 ThreadFactory 給執行緒取有意義的名字,是線上排查問題時最划算的投資之一。

四、系統提供的四種執行緒池

1. FixedThreadPool

fixed 有「固定」之意,透過 Executors.newFixedThreadPool(n) 建立。它只有核心執行緒且沒有超時策略,執行緒不會被回收,因此能穩定快速地回應請求。

範例:4 個任務、2 條執行緒。

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Log.d("hello", "sleep前");
        SystemClock.sleep(3000);
        Log.d("hello", "sleep後");
    }
};
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(runnable);
executorService.execute(runable1);
executorService.execute(runable2);
executorService.execute(runable3);

輸出:

06-24 15:49:47.962 D/hello: sleep1前
06-24 15:49:47.962 D/hello: sleep前
06-24 15:49:50.962 D/hello: sleep1後
06-24 15:49:50.962 D/hello: sleep2前
06-24 15:49:50.972 D/hello: sleep後
06-24 15:49:50.972 D/hello: sleep3前
06-24 15:49:53.962 D/hello: sleep2後
06-24 15:49:53.972 D/hello: sleep3後

每次只有兩條在跑,一條空出來才轮到下一個。把核心數改成 4,四個任務就會一次跑完。

2. CachedThreadPool

執行緒數量不固定,只有非核心執行緒,可粗略理解為上限無限大。它的任務佇列近乎空集合,任何任務進來立刻開一條執行緒跑,適合大量但單個耗時很短的任務。閒置超過 60 秒的非核心執行緒會被回收。

把上面的建立方式換成:

ExecutorService executorService = Executors.newCachedThreadPool();

輸出:

06-24 15:53:08.582 D/hello: sleep2前
06-24 15:53:08.582 D/hello: sleep1前
06-24 15:53:08.582 D/hello: sleep前
06-24 15:53:08.582 D/hello: sleep3前
06-24 15:53:11.582 D/hello: sleep2後
06-24 15:53:11.582 D/hello: sleep1後
06-24 15:53:11.582 D/hello: sleep後
06-24 15:53:11.582 D/hello: sleep3後

四條同時起跑,順序完全不定。若任務突然湧入大量請求,這種池可能一口氣開出幾百條執行緒把系統拖垮,使用時要有警覺。

3. ScheduledThreadPool

Scheduled 是「預定的」。核心執行緒數固定,非核心執行緒無上限,閒置時立即回收。專門用於定時任務與固定週期重複任務。

延遲 2000ms 後執行:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
scheduledExecutorService.schedule(runable1, 2000, TimeUnit.MILLISECONDS);
scheduledExecutorService.schedule(runable2, 2000, TimeUnit.MILLISECONDS);
scheduledExecutorService.schedule(runable3, 2000, TimeUnit.MILLISECONDS);

延遲 10ms 後,每 1000ms 執行一次:

scheduledExecutorService.scheduleAtFixedRate(runnable, 10, 1000, TimeUnit.MILLISECONDS);

scheduleAtFixedRate 是「固定頻率」,scheduleWithFixedDelay 是「上一輪結束後再間隔一段時間」,兩者語意不同,選錯會造成非預期的重疊執行。

4. SingleThreadExecutor

只有一條核心執行緒,所有任務排隊順序執行、絕不亂序。最大好處是省掉了執行緒同步的煩惱,適合有順序依賴或不想處理鎖的場景。

輸出:

06-24 16:05:02.782 D/hello: sleep前
06-24 16:05:05.782 D/hello: sleep後
06-24 16:05:05.782 D/hello: sleep1前
06-24 16:05:08.782 D/hello: sleep1後
06-24 16:05:08.782 D/hello: sleep2前
06-24 16:05:11.782 D/hello: sleep2後
06-24 16:05:11.782 D/hello: sleep3前
06-24 16:05:14.782 D/hello: sleep3後

五、實務選擇建議

  • 需要隔離與可控並發(例如圖片下載)→ 自訂 ThreadPoolExecutor,明確給定 corePoolSize、maximumPoolSize 與有界佇列。
  • 背景定時輪詢 → ScheduledThreadPool。
  • 需要嚴格順序 → SingleThreadExecutor。
  • Android 上還可以直接用 AsyncTask 的 THREAD_POOL_EXECUTOR,或使用各家開源的任務調度框架。

另外記得:任務一定要能收斂。無界佇列加上無限擴充的執行緒,是線上 OOM 的經典配方。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved