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

Android 執行緒池詳解:從 ThreadPoolExecutor 參數到自訂 FIFO/LIFO 佇列

編輯:關於 Android 程式設計

一、直接 new Thread 的問題

需要執行耗時任務時,最直覺的寫法是:

new Thread(new Runnable() {
    @Override
    public void run() {
        // 耗時代碼
    }
}).start();

這種寫法到處可見,但它有問題。執行緒是作業系統調度的最小單位,不能無限產生,而且建立與銷毀都有資源成本。頻繁建立銷毀還會讓 GC 頻繁運行,造成畫面卡頓。

幾個典型場景:網路請求要放到子執行緒;ListView 載入圖片時,若沿用 new Thread,滑動一下就可能瞬間開出數十個執行緒,畫面立刻卡住;下載任務通常需要優先級排程,高優先級先下、低優先級暫停排隊,而傳統 Thread 做不到這件事。

直接使用 Thread 的缺點可以歸納為:

  • 建立太多執行緒會浪費資源,有些甚至沒被充分利用。
  • 銷毀太多執行緒,之後又要花時間重新建立。
  • 建立太慢會造成長時間等待,效能變差。
  • 銷毀太慢會讓其他執行緒資源饑餓。

二、執行緒池簡介

顧名思義,執行緒池就是用來管理執行緒的。池中的執行緒不會被隨意建立,它可以快取一定數量、降低資源消耗,還能指定優先級,或在有大量耗時任務時決定採用 FIFO 還是 LIFO 的排程策略。

Android 的執行緒池概念來自 Java,主要透過 Executor 派生出具體的池實作,使用起來相當方便。優點可歸納為三點:

  • 重用池中執行緒,避免建立與銷毀帶來的效能開銷。
  • 有效控制最大並發數,避免大量執行緒互相搶占資源而導致阻塞。
  • 提供簡單的執行緒管理,並支援定時執行與固定間隔循環執行等功能。

Executor 只是一個介面,真正的實作是 ThreadPoolExecutor,它透過一組參數讓我們細節地配置執行緒池。

三、ThreadPoolExecutor

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

以下所稱的「任務」,指的是實作 Runnable 的物件。

corePoolSize

核心執行緒數。預設情況下核心執行緒會一直存活,即使閒置也不會被回收,也就是說它們會持續存在直到執行緒池被銷毀。若把 allowCoreThreadTimeOut 設為 true,閒置的核心執行緒在超過 keepAliveTime 之後也會被回收:

threadPoolExecutor.allowCoreThreadTimeOut(true);

要注意,並不是只有核心執行緒才能執行任務,而是核心執行緒最穩定、通常不銷毀,因此新任務來臨時能省去建立成本。所以核心執行緒數只要保證大於 0 即可。

maximumPoolSize

執行緒池能容納的最大執行緒數。達到這個上限後,新任務無法再加入,會被執行緒池拒絕。注意最大執行緒數必須大於或等於核心執行緒數。

keepAliveTime 與 unit

這兩個參數控制執行緒存活時間,預設只作用於非核心執行緒:閒置時間超過設定值,執行緒就會被回收。unit 是時間單位,枚舉從天到納秒都有,常用的是 MILLISECONDS、SECONDS 與 MINUTES。若把 allowCoreThreadTimeOut 設為 true,這兩個參數同樣會作用到核心執行緒。

workQueue

任務佇列。透過 execute() 提交的 Runnable 會先存在這裡。

執行緒池的排程規則

提交任務時依序判斷:

  • 若執行緒數未達核心數,直接啟動一個核心執行緒執行該任務。
  • 若已達核心數,任務進入佇列排隊;核心執行緒空閒時再依佇列規則取出執行。
  • 若佇列已滿(或其他原因導致無法入列),且執行緒數尚未達上限,立刻開啟新執行緒執行。
  • 若執行中的執行緒數已達上限,則執行緒池拒絕該任務。

threadFactory

執行緒工廠,負責為執行緒池建立執行緒。它是一個只有單一方法的介面:

Thread newThread(Runnable r);

RejectedExecutionHandler

當執行緒池無法執行新任務(佇列已滿或其他原因),會呼叫 handler 的 rejectedExecution 通知呼叫方。內建四種策略:

CallerRunsPolicy

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    if (!e.isShutdown()) {
        r.run();
    }
}

由提交任務的那個執行緒自己執行,形成簡單的回饋控制:提交端被佔住,自然減慢了新任務的提交速度。

AbortPolicy

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    throw new RejectedExecutionException();
}

直接拋出例外並丟棄任務。這是執行緒池的預設策略。

DiscardPolicy

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { }

靜默丟棄任務,不拋例外。

DiscardOldestPolicy

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    if (!e.isShutdown()) {
        e.getQueue().poll();
        e.execute(r);
    }
}

丟掉佇列中最舊的任務,然後重試提交當前任務,並可能反覆進行。使用這個策略要格外小心,因為被丟棄的任務不會有任何提示。

四、四類內建執行緒池

Android 中最常見的四類執行緒池,都是透過配置 ThreadPoolExecutor 來實作各自特性。

FixedThreadPool

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

核心數與最大數相同,所有執行緒都是核心執行緒,因此沒有超時機制;佇列是無界的,任務可以無上限排隊。

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 10; i++) {
    final int index = i;
    fixedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("執行緒:" + Thread.currentThread().getName() + ",任務:" + index);
            try {
                Thread.sleep(2000);      // 模擬耗時
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

一開始執行 3 個任務,其餘 7 個進入等待。核心執行緒完成一個後,就依 FIFO 從佇列取下一個,所以除了前三個,其餘任務是順序執行的。

CachedThreadPool

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

核心數為 0(沒有核心執行緒),最大數是 int 上限,可視為無上限。新任務來時,有閒置執行緒就交給它,沒有就開新執行緒。SynchronousQueue 是一個特殊佇列,多數情況下可以簡單理解為「幾乎無法插入」的佇列。

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 1; i <= 10; i++) {
    final int index = i;
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    cachedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("執行緒:" + Thread.currentThread().getName() + ",任務:" + index);
            try {
                Thread.sleep(index * 500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

可以看到,當存在存活的閒置執行緒時,任務會被派去 reuse(例如任務 2 與任務 1 在同一執行緒執行);若沒有閒置執行緒,就開啟新執行緒。這類池適合執行大量「短而多」的任務,閒置時執行緒會被回收,幾乎不佔用系統資源。

ScheduledThreadPool

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());
}

核心數固定、最大數視為無限制,與前面幾種的差別在於佇列是 DelayedWorkQueue,能讓任務延遲或週期性執行。

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("任務開始");
scheduledThreadPool.schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println("任務:" + Thread.currentThread().getName());
    }
}, 3, TimeUnit.SECONDS);

程式先印出「任務開始」,3 秒後才執行提交的任務,這就是延遲功能。它也能週期性執行:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("任務開始");
// 延遲 4 秒首次執行,之後每隔 1 秒執行一次
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println("執行任務");
    }
}, 4, 1, TimeUnit.SECONDS);

提交後等 4 秒開始循環,之後每兩次執行之間間隔 1 秒。

SingleThreadExecutor

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

看程式碼就知道,它就是參數為 1 的 FixedThreadPool——只有一條執行緒,任務依提交順序執行。外層的 FinalizableDelegatedExecutorService 只是為了避免使用者把它向下轉型成 ThreadPoolExecutor 去改參數。

小結

官方實際上不太建議我們自行配置 ThreadPoolExecutor,而是建議使用它提供的這幾類,通常已能滿足大多數需求,使用上也更簡單。

五、任務佇列

觀察這幾種池會發現,決定它們功能差異的最主要因素就是任務佇列。任務佇列實作的是 BlockingQueue 介面,裡面規定了加入與取出等共 11 個方法,全部覆寫非常麻煩,所幸 Java 已封裝了幾個常用實作:

  • LinkedBlockingQueue:無界佇列
  • SynchronousQueue:直接提交佇列
  • DelayedWorkQueue:等待佇列
  • PriorityBlockingQueue:優先級佇列
  • ArrayBlockingQueue:有界佇列

LinkedBlockingQueue 與 ArrayBlockingQueue

這兩個很像 LinkedList 與 ArrayList 的關係:一個用鏈表實作、一個用陣列實作,都是 FIFO。差別在於 LinkedBlockingQueue 可以沒有數量上限。而根據前面說的排程規則,一旦佇列無上限,任務永遠不會「填滿佇列」,也就永遠用不到非核心執行緒——這正是 Java 封裝的 FixedThreadPool 與 SingleThreadExecutor 都把核心數與最大數設成相同的原因。

SynchronousQueue

這個佇列會把任務直接交給執行緒而不保留。若當下沒有可立即執行的執行緒,加入就會失敗,於是必須建立新執行緒。此策略在處理具有內部依賴性的請求集時,可以避免鎖競爭。直接提交通常需要無界的 maximumPoolSize,否則會不斷拒絕新任務——這也就是 CachedThreadPool 把最大數設為 Integer.MAX_VALUE 的原因。

PriorityBlockingQueue

優先級佇列會在提交時比較每個任務的優先級,優先級高的先被取出。因為任務都是 Runnable,要讓佇列知道誰優先,得讓任務具備可比性:

public abstract class PriorityRunnable implements Runnable, Comparable<PriorityRunnable> {

    private int priority;

    public PriorityRunnable(int priority) {
        if (priority < 0) {
            throw new IllegalArgumentException();
        }
        this.priority = priority;
    }

    @Override
    public int compareTo(PriorityRunnable another) {
        return another.getPriority() - priority;   // 數值越小越優先
    }

    public int getPriority() {
        return priority;
    }
}

抽象類實作 Runnable 才能被提交,實作 Comparable 才能告訴佇列大小關係。這裡用 int 表示優先級並覆寫 compareTo;實際上並不一定要用 int,String 或其他型別也行,重點是實作 Comparable。使用方式:

ExecutorService priorityThreadPool = new ThreadPoolExecutor(3, 3, 0L,
        TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>());

for (int i = 1; i <= 10; i++) {
    final int priority = i;
    priorityThreadPool.execute(new PriorityRunnable(priority) {
        @Override
        public void run() {
            System.out.println("執行緒:" + Thread.currentThread().getName()
                    + ",正在執行優先級為:" + priority + "的任務");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

前三個任務沒進佇列,直接由核心執行緒接手;剩下 7 個進入優先級佇列,取出時會依優先級排序,數字小的先執行。如果讓每個任務帶入當前時間戳作為優先級,還能實作出類似 LIFO 的效果。

六、執行緒池的其他方法

ThreadPoolExecutor 另外提供了三個可覆寫的+---------+:

  • beforeExecute():任務執行前呼叫
  • afterExecute():任務執行結束後呼叫
  • terminated():執行緒池關閉後呼叫

要使用它們,需自訂一個類別繼承 ThreadPoolExecutor 並覆寫:

public class MyThreadPool extends ThreadPoolExecutor {

    public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                        TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        // 任務執行前
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // 任務執行後
    }

    @Override
    protected void terminated() {
        super.terminated();
        // 執行緒池關閉
    }
}

七、用 Semaphore 控制提交節奏

任務的提交方式主要由佇列決定,但佇列方法多、覆寫麻煩,而且官方也建議直接用內建的幾類池。如果我們需要動態在 FIFO 與 LIFO 之間切換,或者提交策略複雜到內建模組無法滿足,常見做法是:自己寫一個佇列,不實作 ThreadPoolExecutor 介面,也不當成佇列參數傳進去;所有任務先進我們自己的佇列,等執行緒池空閒時再轉交。

問題來了:我們怎麼知道執行緒池裡有沒有空閒執行緒?這就要用 Semaphore(號誌燈)。

號誌燈是什麼

想像百貨公司的停車場只有 3 個車位,但來了 6 台車。入口的電子看板會顯示還有多少空位;若已停滿,新車就得在入口等待,直到看板顯示有空位。號誌燈就是這塊看板:它記錄可用數量,數量歸零時,請求的執行緒會停在該處等待。

// 只有 2 個位置的號誌燈
final Semaphore semp = new Semaphore(2);
for (int i = 0; i < 4; i++) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            try {
                semp.acquire();                     // 申請號誌燈
                System.out.println(threadName + "申請到了號誌燈");
                Thread.sleep(2000);                 // 模擬耗時
                semp.release();                     // 釋放號誌燈
                System.out.println(threadName + "釋放了號誌燈");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

前兩個執行緒成功取得號誌燈並開始執行,後兩個停在 acquire() 這一步,直到有號誌燈被釋放才繼續。也就是說必須等前面的執行緒完成,後面的才會往下走——這和只有 2 條核心執行緒的執行緒池幾乎一樣。

自訂可切換 FIFO / LIFO 的執行緒池

先看效果:

點擊 FIFO 時任務從 0 遞增到 99;點擊 LIFO 時立刻從後往前執行。版面配置很簡單,兩個 Button 加一個 TextView:

<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <LinearLayout android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <Button android:id="@+id/btn_FIFO"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="FIFO" />

        <Button android:id="@+id/btn_LIFO"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="LIFO" />
    </LinearLayout>

    <TextView android:id="@+id/main_text"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Hello World!" />
</LinearLayout>

Activity 中建立自訂執行緒池、塞進 100 個任務,核心與最大執行緒都設為 1,每個任務把自己的編號透過 Handler 送到主執行緒顯示;按鈕則呼叫 setWay() 切換策略:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button FIFOBtn, LIFOBtn;
    private TextView mainTv;
    private MyThreadPool myThreadPool;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FIFOBtn = (Button) findViewById(R.id.btn_FIFO);
        LIFOBtn = (Button) findViewById(R.id.btn_LIFO);
        mainTv = (TextView) findViewById(R.id.main_text);
        FIFOBtn.setOnClickListener(this);
        LIFOBtn.setOnClickListener(this);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                mainTv.setText("任務:" + msg.what);
                return false;
            }
        });

        myThreadPool = new MyThreadPool(1);
        for (int i = 0; i < 100; i++) {
            final int index = i;
            myThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(index);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_FIFO:
                myThreadPool.setWay(MyThreadPool.OutWay.FIFO);
                break;
            case R.id.btn_LIFO:
                myThreadPool.setWay(MyThreadPool.OutWay.LIFO);
                break;
        }
    }
}

關鍵在自訂的執行緒池:

public class MyThreadPool extends ThreadPoolExecutor {

    private volatile Semaphore semaphore;
    private List<Runnable> runnableList;
    private LoopThread loopThread;
    private boolean flag;

    enum OutWay { FIFO, LIFO }

    private OutWay outWay;

    public MyThreadPool(int corePoolSize) {
        super(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        semaphore = new Semaphore(corePoolSize);   // 號誌燈數量 = 核心執行緒數
        runnableList = new LinkedList<>();
        flag = true;
        outWay = OutWay.FIFO;                      // 預設先進先出
        loopThread = new LoopThread();
        loopThread.start();
    }

    // 任務不進執行緒池,先放進自己的佇列
    @Override
    public synchronized void execute(Runnable command) {
        runnableList.add(command);
        if (runnableList.size() < 2) {
            synchronized (loopThread) {
                loopThread.notify();               // 喚醒輪詢執行緒
            }
        }
    }

    public void setWay(OutWay outWay) {
        this.outWay = outWay;
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        semaphore.release();                       // 任務完成,釋放號誌燈
    }

    @Override
    protected void terminated() {
        super.terminated();
        flag = false;                              // 停止輪詢執行緒
    }

    class LoopThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (flag) {
                if (runnableList.size() == 0) {
                    synchronized (this) {
                        try {
                            wait();                // 沒任務就等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    try {
                        semaphore.acquire();       // 確認有空閒執行緒
                        int index;
                        switch (outWay) {
                            case FIFO:
                                index = 0;
                                break;
                            default:
                                index = runnableList.size() - 1;
                                break;
                        }
                        // 注意:呼叫父類的 execute 才會真正進執行緒池
                        MyThreadPool.super.execute(runnableList.get(index));
                        runnableList.remove(index);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

設計要點:

  • 核心數與最大數相同(由建構參數決定,這裡是 1),號誌燈數量也設為核心數。
  • 內部用一個 List 存放提交進來的任務,並覆寫 execute(),讓任務不再直接進池,而是先落到 runnableList。
  • 另開一條輪詢執行緒負責轉交:佇列為空時 wait,有任務時先 acquire 一個號誌燈(確認池中有空閒執行緒),再依 FIFO 或 LIFO 從佇列取任務,呼叫父類的 execute() 真正提交。
  • 釋放時機在 afterExecute():池中一個任務完成後回調此方法,釋放號誌燈,輪詢執行緒便會再補一個任務進來。

八、關閉執行緒池

專案整個結束後通常需要關閉執行緒池,有兩個方法:shutdown() 會讓池內剩餘任務執行完再關閉;shutdownNow() 則放棄未完成的任務立即關閉(並回傳未執行的任務清單)。

九、最後:核心數怎麼定

實務上通常依 CPU 核心數來設定核心執行緒數,常見做法是「CPU 核心數 + 1」。Android 中可以這樣取得核心數:

Runtime.getRuntime().availableProcessors();

+1 的理由是:即使所有核心都在忙,多保留一條執行緒也能在某一條偶爾因缺頁或 GC 而阻塞時,繼續把 CPU 填滿。

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