Android 啟動與停止線程池中的線程

2018-08-02 18:27 更新

編寫:AllenZheng1991 - 原文:http://developer.android.com/training/multiple-threads/run-code.html

在前面的課程中向你展示了如何去定義一個(gè)可以管理線程池且能在他們中執(zhí)行任務(wù)代碼的類。在這一課中我們將向你展示如何在線程池中執(zhí)行任務(wù)代碼。為了達(dá)到這個(gè)目的,你需要把任務(wù)添加到線程池的工作隊(duì)列中去,當(dāng)一個(gè)線程變成可運(yùn)行狀態(tài)時(shí),ThreadPoolExecutor從工作隊(duì)列中取出一個(gè)任務(wù),然后在該線程中執(zhí)行。

這節(jié)課同時(shí)也向你展示了如何去停止一個(gè)正在執(zhí)行的任務(wù),這個(gè)任務(wù)可能在剛開始執(zhí)行時(shí)是你想要的,但后來發(fā)現(xiàn)它所做的工作并不是你所需要的。你可以取消線程正在執(zhí)行的任務(wù),而不是浪費(fèi)處理器的運(yùn)行時(shí)間。例如你正在從網(wǎng)絡(luò)上下載圖片且對下載的圖片進(jìn)行了緩存,當(dāng)檢測到正在下載的圖片在緩存中已經(jīng)存在時(shí),你可能希望停止這個(gè)下載任務(wù)。當(dāng)然,這取決于你編寫APP的方式,因?yàn)榭赡軌涸谀銌酉螺d任務(wù)之前無法獲知是否需要啟動這個(gè)任務(wù)。

啟動線程池中的線程執(zhí)行任務(wù)

為了在一個(gè)特定的線程池的線程里開啟一個(gè)任務(wù),可以通過調(diào)用ThreadPoolExecutor.execute(),它需要提供一個(gè)Runnable類型的參數(shù),這個(gè)調(diào)用會把該任務(wù)添加到這個(gè)線程池中的工作隊(duì)列。當(dāng)一個(gè)空閑的線程進(jìn)入可執(zhí)行狀態(tài)時(shí),線程管理者從工作隊(duì)列中取出等待時(shí)間最長的那個(gè)任務(wù),并且在線程中執(zhí)行它。

public class PhotoManager {
    public void handleState(PhotoTask photoTask, int state) {
        switch (state) {
            // The task finished downloading the image
            case DOWNLOAD_COMPLETE:
            // Decodes the image
                mDecodeThreadPool.execute(
                        photoTask.getPhotoDecodeRunnable());
            ...
        }
        ...
    }
    ...
}

當(dāng)ThreadPoolExecutor在一個(gè)線程中開啟一個(gè)Runnable后,它會自動調(diào)用Runnable的run()方法。

中斷正在執(zhí)行的代碼

為了停止執(zhí)行一個(gè)任務(wù),你必須中斷執(zhí)行這個(gè)任務(wù)的線程。在準(zhǔn)備做這件事之前,當(dāng)你創(chuàng)建一個(gè)任務(wù)時(shí),你需要存儲處理該任務(wù)的線程。例如:

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

想要中斷一個(gè)線程,你可以調(diào)用Thread.interrupt())。需要注意的是這些線程對象都被系統(tǒng)控制,系統(tǒng)可以在你的APP進(jìn)程之外修改 他們。因?yàn)檫@個(gè)原因,在你要中斷一個(gè)線程時(shí),你需要把這段代碼放在一個(gè)同步代碼塊中對這個(gè)線程的訪問加鎖來解決這個(gè)問題。例如:

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

在大多數(shù)情況下,通過調(diào)用Thread.interrupt()能立即中斷這個(gè)線程,然而他只能停止那些處于等待狀態(tài)的線程,卻不能中斷那些占據(jù)CPU或者耗時(shí)的連接網(wǎng)絡(luò)的任務(wù)。為了避免拖慢系統(tǒng)速度或造成系統(tǒng)死鎖,在嘗試執(zhí)行耗時(shí)操作之前,你應(yīng)該測試當(dāng)前是否存在處于掛起狀態(tài)的中斷請求:

/*
 * 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);
...


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號