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

Android 線程池詳解:四種內建線程池與取捨

編輯:關於 Android 程式設計

在 ListView 中載入圖片時,如果沒有緩存機制,每個 Item 都可能開一條線程去下載。Item 一多,線程就會無限增長,最終導致畫面卡頓、手機反應遲鈍,最糟的結果是用戶直接把 App 卸掉。所以實務開發中繞不開線程池。

使用線程池的好處:

(1) 重用線程,避免反覆創建與銷毀帶來的效能開銷;
(2) 有效控制最大併發數,避免大量線程互相搶奪資源造成的阻塞;
(3) 便於管理線程,並提供定時執行、固定間隔循環執行等能力。

Android 的線程池來自 Java,Java 裡有四種:

(1) SingleThreadExecutor:單線程化線程池,只用唯一的工作線程執行任務,保證任務按指定順序(FIFO、LIFO、優先級)執行;
(2) CachedThreadPool:可緩存線程池,線程多餘時可回收空閒線程,無可回收則新建;
(3) FixedThreadPool:定長線程池,可控制最大併發數,超出的線程在隊列中等待;
(4) ScheduledThreadPool:定長線程池,支援定時與周期性任務。

創建線程池統一走 Executors 類,而它的核心構造方法是 ThreadPoolExecutor:

ThreadPoolExecutor(int corePoolSize,
                   int maximumPoolSize,
                   long keepAliveTime,
                   TimeUnit unit,
                   BlockingQueue<Runnable> workQueue,
                   ThreadFactory threadFactory,
                   RejectedExecutionHandler handler)

參數說明:

corePoolSize:線程池維護的最小線程數。預設情況下核心線程即使閒置也一直存活;若把 allowCoreThreadTimeOut 設為 true,閒置核心線程也會有超時策略,時間由 keepAliveTime 指定,超過後核心線程會被終止。

maximumPoolSize:線程池能維護的最大線程數,達到這個值後新任務將被阻塞。

keepAliveTime:超過 corePoolSize 數量的空閒線程最大存活時間。

unit:時間單位,TimeUnit 提供 7 種取值:

TimeUnit.DAYS;         // 天
TimeUnit.HOURS;        // 小時
TimeUnit.MINUTES;      // 分鐘
TimeUnit.SECONDS;      // 秒
TimeUnit.MILLISECONDS; // 毫秒
TimeUnit.MICROSECONDS; // 微秒
TimeUnit.NANOSECONDS;  // 納秒

workQueue:緩衝隊列,透過 execute 提交的 Runnable 會存在這裡。

threadFactory:新建線程的工廠,ThreadFactory 只有一個方法 Thread newThread(Runnable r)。

handler:當提交任務數超過 maximumPoolSize + workQueue 之和時,交給 RejectedExecutionHandler 處理。

三者之間的關係是這樣的:

(1) 線程池小於 corePoolSize 時,新任務直接創建新線程執行,即使此時有空閒線程;
(2) 達到 corePoolSize 後,新任務進入 workQueue 等待調度;
(3) workQueue 已滿且 maximumPoolSize > corePoolSize 時,新任務再創建新線程執行;
(4) 任務數超過 maximumPoolSize 時,交由 RejectedExecutionHandler 處理;
(5) 超出 corePoolSize 的線程閒置達到 keepAliveTime 後關閉;
(6) 若 allowCoreThreadTimeOut 為 true,核心線程閒置超過 keepAliveTime 也會關閉。

1. SingleThreadExecutor

ExecutorService pool = Executors.newSingleThreadExecutor();

建立一個使用單個 worker 線程的 Executor,以無界隊列運行該線程。若該線程因執行失敗而終止,需要時會新建一條線程代替它。它能保證任務順序執行,且任意時刻只有一個線程活動。

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

corePoolSize = maximumPoolSize = 1,搭配無界阻塞隊列 LinkedBlockingQueue,任務由單一線程串行執行。

public static void singThreadExecutors() {
    ExecutorService pool = Executors.newSingleThreadExecutor();
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    pool.shutdown();
}

class MyThread extends Thread {
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " is running...");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

每隔兩秒打印一次,輸出順序固定,等同順序執行。

現今多數 GUI 程式都是單線程的。Android 中單線程適合用於資料庫操作、文件操作、批量安裝、批量刪除等「不適合併發但可能 IO 阻塞」的場景。

這類線程池內部只有一個核心線程,確保所有任務在同一線程中順序執行。它的意義在於把外界任務統一收斂到一個線程,這樣任務之間就不需要處理線程同步問題。

2. CachedThreadPool

ExecutorService pool = Executors.newCachedThreadPool();

當線程池大小超過處理任務所需,會回收部分空閒(60 秒不執行任務)的線程;任務數增加時又能智慧地添新線程。它不限制線程池大小,上限完全取決於系統能創建的最大線程數。

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
}

核心線程為 0,最大線程數為 Integer.MAX_VALUE,keepAliveTime 為 60 秒,緩存隊列是 SynchronousQueue。因為多個線程共用一個 SynchronousQueue,必須保證對它的訪問是串行的:前一個線程沒用完,後一個線程就得等。

public static void cachedThreadPool() {
    ExecutorService pool = Executors.newCachedThreadPool();
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    pool.shutdown();
}

它是線程數量不定的線程池,只有非核心線程,最大線程數極大,實際上等於可任意擴展。當所有線程都在活動時,會新建線程處理新任務,否則複用空閒線程。空閒線程有 60 秒超時機制,超過即被回收。與 FixedThreadPool 不同的是,它的任務隊列相當於一個空集合,任何任務都會被立即執行,因為 SynchronousQueue 根本插不進任務。這類線程池適合執行大量「耗時短」的任務;當線程池整體閒置時,所有線程都會超時終止,此時它幾乎不佔用任何系統資源。

3. FixedThreadPool

ExecutorService pool = Executors.newFixedThreadPool(int nThreads);

建立一個可重用固定線程數的線程池,nThreads 就是線程數(大小最好依系統資源來設定)。

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
}

corePoolSize 與 maximumPoolSize 相同,keepAliveTime 為 0,表示不做 keep alive。

public static void fixedThreadPool() {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    Thread t3 = new MyThread();
    Thread t4 = new MyThread();
    Thread t5 = new MyThread();
    pool.execute(t1);
    pool.execute(t2);
    pool.execute(t3);
    pool.execute(t4);
    pool.execute(t5);
    pool.shutdown();
}

線程數固定為 3,先創建 3 條線程執行,執行完轉為空閒再接手後續等待中的任務。

它是線程數量固定的線程池。線程閒置時不會被回收,除非線程池被關閉;所有線程都在活動時,新任務進入等待狀態直到有線程空出來。由於只有核心線程且不回收,它能更快速地響應外界請求。

4. ScheduledThreadPool

ScheduledExecutorService pool = Executors.newScheduledThreadPool(int corePoolSize);

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS,
          MILLISECONDS, new DelayedWorkQueue());
}

使用示例:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
// 2000ms 後執行一次
scheduledExecutorService.schedule(command, 2000, TimeUnit.MILLISECONDS);
// 延遲 10ms 後,每隔 1000ms 執行一次
scheduledExecutorService.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);

它的核心線程數固定,非核心線程數不受限制,且非核心線程閒置時會被立即回收。這類線程池主要用於定時任務與固定週期的重複任務。

總結

(1) 最大線程數一般設為 2N + 1 較合適,N 是 CPU 核數;
(2) 看過 AsyncTask 源碼就會發現,它內部也是一個線程池;
(3) 線程池建立後初始為 RUNNING 狀態;
(4) 呼叫 shutdown() 後進入 SHUTDOWN 狀態,不再接受新任務,但會等待所有任務執行完畢;
(5) 呼叫 shutdownNow() 後進入 STOP 狀態,不接受新任務,並嘗試中止正在執行的任務;
(6) 當線程池處於 SHUTDOWN 或 STOP,且所有工作線程已銷毀、隊列已清空或執行完畢,線程池進入 TERMINATED 狀態。

線程池的核心作用就是限制系統中同時執行的線程數量。依環境情況自動或手動設定線程數,才能達到最佳效果:太少浪費資源,太多造成系統擁擠反而效率低下。用線程池控制數量,其餘任務排隊等候,一個任務完成後再從隊列頭部取下一個執行;隊列中沒有等待任務時,該資源就處於等待狀態。

附帶說明「並行」與「併發」的差異:

1. 並行指兩者同時執行同一件事,比如賽跑,兩個人都在不停地往前跑;
2. 併發指資源有限時兩者交替輪流使用資源,比如一段單線道路同時只能過一個人,A 走一段讓給 B,B 用完再換 A,交替使用以提高效率。

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