Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

在 Android 線程池中執行任務並隨時中斷的實踐

編輯: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);
...

把這個判斷散布在長任務的各個階段,就能讓取消操作既及時又不粗暴。

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