Android官方开发文档Training系列课程中文版:线程执行操作之线程池操作
原文地址:http://android.xsoftlab.net/training/multiple-threads/run-code.html#StopThread
上節(jié)課我們學(xué)習(xí)了如何定義一個類用于管理線程以及任務(wù)。這節(jié)課將會學(xué)習(xí)如何在線程池中運行任務(wù)。要做到這一點,只需要往線程池的工作隊列中添加任務(wù)即可。當(dāng)一條線程處于閑置狀態(tài)時,那么ThreadPoolExecutor會從任務(wù)隊列中取出一條任務(wù)并放入該線程中運行。
這節(jié)課還介紹了如何停止一個正在運行中的任務(wù)。如果在任務(wù)開始后,可能發(fā)現(xiàn)這項任務(wù)并不是必須的,那么就需要用到任務(wù)取消的功能了。這樣可以避免浪費處理器的時間。舉個例子,如果你正從網(wǎng)絡(luò)上下載一張圖像,如果偵測到這張圖像已經(jīng)在緩存中了,那么這時就需要停止這項網(wǎng)絡(luò)任務(wù)了。
在線程池中的線程內(nèi)運行任務(wù)
為了在指定的線程池中啟動一項線程任務(wù),需要將Runnable對象傳給ThreadPoolExecutor的execute()方法。這個方法會將任務(wù)添加到線程池的工作隊列中去。當(dāng)其中一個線程變?yōu)殚e置狀態(tài)時,那么線程池管理器會從隊列中取出一個已經(jīng)等待了很久的任務(wù),然后放到這個線程中運行:
public class PhotoManager {public void handleState(PhotoTask photoTask, int state) {switch (state) {// The task finished downloading the imagecase DOWNLOAD_COMPLETE:// Decodes the imagemDecodeThreadPool.execute(photoTask.getPhotoDecodeRunnable());...}...}... }當(dāng)ThreadPoolExecutor啟動一個Runnable時,它會自動調(diào)用Runnable的run()方法。
中斷執(zhí)行中的代碼
如果要停止一項任務(wù),那么需要中斷該任務(wù)所在的線程。為了可以預(yù)先做到這一點,那么需要在任務(wù)創(chuàng)建時存儲該任務(wù)所在線程的句柄:
class PhotoDecodeRunnable implements Runnable {// Defines the code to run for this taskpublic void run() {/** Stores the current Thread in the* object that contains PhotoDecodeRunnable*/mPhotoTask.setImageDecodeThread(Thread.currentThread());...}... }我們可以調(diào)用Thread.interrupt()方法來中斷一個線程。這里要注意Thread對象是由系統(tǒng)控制的,系統(tǒng)會在應(yīng)用進程的范圍之外修改它們。正因為這個原因,在中斷線程之前,需要對線程的訪問加鎖。通常需要將這部分代碼放入同步代碼塊中:
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 queuemDecodeWorkQueue.toArray(runnableArray);// Stores the array length in order to iterate over the arrayint len = runnableArray.length;/** Iterates over the array of Runnables and interrupts each one's Thread.*/synchronized (sInstance) {// Iterates over the array of tasksfor (int runnableIndex = 0; runnableIndex < len; runnableIndex++) {// Gets the current threadThread thread = runnableArray[taskArrayIndex].mThread;// if the Thread exists, post an interrupt to itif (null != thread) {thread.interrupt();}}}}... }在多數(shù)情況下,Thread.interrupt()會使線程立刻停止。然而,它只會將那些正在等待的線程停下來,它并不會中止CPU或網(wǎng)絡(luò)任務(wù)。為了避免使系統(tǒng)變慢或卡頓,你應(yīng)當(dāng)在開始任意一項操作之前測試是否有中斷請求:
/** 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); ...總結(jié)
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:线程执行操作之线程池操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: Hadoop 命令操作