日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android官方开发文档Training系列课程中文版:线程执行操作之线程池操作

發布時間:2024/7/5 Android 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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系列课程中文版:线程执行操作之线程池操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。