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

上一篇向你展示了如何定一个类,管理线程池和运行在里面的任务。这一篇向你展示如何运行县城池里的一个任务。为了实现这个 ,你需要添加一个任务到线程池工作队列中。当一个线程变为可用状态时,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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值