Android官方开发文档Training系列课程中文版:线程执行操作之线程池操作
原文地址:http://android.xsoftlab.net/training/multiple-threads/run-code.html#StopThread
上節課我們學習了如何定義一個類用于管理線程以及任務。這節課將會學習如何在線程池中運行任務。要做到這一點,只需要往線程池的工作隊列中添加任務即可。當一條線程處于閑置狀態時,那么ThreadPoolExecutor會從任務隊列中取出一條任務并放入該線程中運行。
這節課還介紹了如何停止一個正在運行中的任務。如果在任務開始后,可能發現這項任務并不是必須的,那么就需要用到任務取消的功能了。這樣可以避免浪費處理器的時間。舉個例子,如果你正從網絡上下載一張圖像,如果偵測到這張圖像已經在緩存中了,那么這時就需要停止這項網絡任務了。
在線程池中的線程內運行任務
為了在指定的線程池中啟動一項線程任務,需要將Runnable對象傳給ThreadPoolExecutor的execute()方法。這個方法會將任務添加到線程池的工作隊列中去。當其中一個線程變為閑置狀態時,那么線程池管理器會從隊列中取出一個已經等待了很久的任務,然后放到這個線程中運行:
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());...}...}... }當ThreadPoolExecutor啟動一個Runnable時,它會自動調用Runnable的run()方法。
中斷執行中的代碼
如果要停止一項任務,那么需要中斷該任務所在的線程。為了可以預先做到這一點,那么需要在任務創建時存儲該任務所在線程的句柄:
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());...}... }我們可以調用Thread.interrupt()方法來中斷一個線程。這里要注意Thread對象是由系統控制的,系統會在應用進程的范圍之外修改它們。正因為這個原因,在中斷線程之前,需要對線程的訪問加鎖。通常需要將這部分代碼放入同步代碼塊中:
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();}}}}... }在多數情況下,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官方开发文档Training系列课程中文版:线程执行操作之线程池操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: android sina oauth2.