編輯:Android 開發實例
線程池的運作方式很像一條流水線:你把任務放進工作隊列,一旦有線程空出來(要麼跑完了手上的活,要麼本來就閒著),ThreadPoolExecutor 就會從隊列裡取出任務並在該線程上執行。本文除了說明如何投遞任務,還會講到怎樣把正在跑的任務安全地停掉。
投遞任務只需要調用 ThreadPoolExecutor.execute(),並傳入一個 Runnable 實例。這個方法會把任務追加到工作隊列中;等有閒置線程時,管理器會取出等待時間最久的那個任務來執行。
public class PhotoManager {
public void handleState(PhotoTask photoTask, int state) {
switch (state) {
case DOWNLOAD_COMPLETE:
// 圖片下載完成,交給線程池去解碼
mDecodeThreadPool.execute(
photoTask.getPhotoDecodeRunnable());
...
}
...
}
...
}
任務一旦被 ThreadPoolExecutor 接手,run() 方法就會被自動調用。
想讓任務停下來,本質上是去中斷它所在的線程。前提是你在創建任務時就把當前線程的引用保存下來。
class PhotoDecodeRunnable implements Runnable {
// Defines the code to run for this task
public void run() {
/*
* Stores the current Thread in the
* object that contains PhotoDecodeRunnable
*/
mPhotoTask.setImageDecodeThread(Thread.currentThread());
...
}
...
}
中斷動作由 Thread.interrupt() 完成。需要注意的是,線程對象由系統託管,可能在你的應用進程之外被改動,因此操作它之前應先加訪問鎖,把它放進同步塊裡:
public class PhotoManager {
public static void cancelAll() {
/*
* Creates an array of Runnables that's the same size as the
* thread pool work queue
*/
Runnable[] runnableArray = new Runnable[mDecodeWorkQueue.size()];
// Populates the array with the Runnables in the queue
mDecodeWorkQueue.toArray(runnableArray);
// Stores the array length in order to iterate over the array
int len = runnableArray.length;
/*
* Iterates over the array of Runnables and interrupts each one's Thread.
*/
synchronized (sInstance) {
// Iterates over the array of tasks
for (int runnableIndex = 0; runnableIndex < len; runnableIndex++) {
// Gets the current thread
Thread thread = runnableArray[taskArrayIndex].mThread;
// if the Thread exists, post an interrupt to it
if (null != thread) {
thread.interrupt();
}
}
}
}
...
}
在大多數場景中,Thread.interrupt() 能立刻讓線程停下,但它真正能立刻終止的只是「正在等待」的線程,對於 CPU 密集型或網絡密集型操作並不一定即時生效。若不希望系統被拖慢,正確做法是在每一段耗时操作開始之前主動檢查一次中斷請求:
/*
* Before continuing, checks to see that the Thread hasn't
* been interrupted
*/
if (Thread.interrupted()) {
return;
}
...
// Decodes a byte array into a Bitmap (CPU-intensive)
BitmapFactory.decodeByteArray(
imageBuffer, 0, imageBuffer.length, bitmapOptions);
...
把這個判斷散布在長任務的各個階段,就能讓取消操作既及時又不粗暴。
Android 加載 Spinner:用進度條顯示未知時長的任務
在 Android 中,可以透過加載進度條來顯示任務的進展。進度條有兩種形狀:加載欄與加載微調(spinner)。本章我們將討論 spinner。 Spinner 用於顯
Android 應用本地化:讓 App 依地區自動切換語言
Android 應用會運行在name各語言環境的裝置上。要讓應用更具親和力,就必須讓文字、數字與檔案等资源能配合裝置的語言環境自動調整。本章將說明如何依不同區域(Loca
BroadcastReceiver 詳解:動態/static 註冊與電量監聽實作
前面幾篇談了 Activity 與 Service,這次來看第三大元件 BroadcastReceiver。廣播是 Android 應用彼此溝通的手段,而它跟 Inten
Android 登入實作:帳號密碼驗證與三次錯誤鎖定
登入畫面負責向使用者索取帳號與密碼以驗證身分,是許多應用(如 Facebook、微博)的必備環節。本章說明如何建立登入介面,並處理安全性與錯誤嘗試次數的限制。 首先在版