多线程之三:在线程池中的线程运行代码 (Running Code on a Thread Pool Thread)

来源:互联网 发布:淘宝买家5星可以贷款吗 编辑:程序博客网 时间:2024/04/27 21:40

上一篇向你展示了如何定一个类,管理线程池和运行在里面的任务。这一篇向你展示如何运行县城池里的一个任务。为了实现这个 ,你需要添加一个任务到线程池工作队列中。当一个线程变为可用状态时,ThreadPoolExecutor就从队列中取出一个任务并在线程上运行该任务。

这一篇也向你展示如何停止一个正在运行的任务。当任务开始之后,但是发现这个任务已经没有必要运行时,你可能需要停止这个正在运行的任务。与其浪费进程时间,不如你可以取消正在运行这任务的线程。例如,你正在从网络下载图片并且使用了缓存,如果你检测到需要的图片已经在缓存里面了你可能想停止这个任务。这些取决与你如何写你的app,在你开始现在之前你可能没有检测到这个图片。


在线程池中运行一个线程任务

为了在特殊的线程池中开始线程任务对象,并传递一个Runnable()到ThreadPoolExecutor.execute()中。这个调用加载了一个任务到线程池的工作队列。当一个休眠的线程变为可用时,管理器取出那个已经等待时间最长的任务,并在该线程上运行这个任务。

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

当ThreadPoolExecutor开始一个Runnable在线程上, 它会自动调用run()方法。

中断正在运行的代码

为了停止一个任务,你需要中断这个任务的线程。为了准备这些,你需要在创建一个任务时存储该任务的一个handler。例如:

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()。注意线程对象是被系统控制,它可以在你的app进程外部修改线程对象。因为这个原因,你需要在中断一个线程之前锁定它入口,通过使用同步锁来占用该入口。例如:

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


0 0
原创粉丝点击