The previous lesson showed you how to define a class that manages thread pools and the tasks that run on them. This lesson shows you how to run a task on a thread pool. To do this, you add the task to the pool's work queue. When a thread becomes available, the ThreadPoolExecutor takes a task from the queue and runs it on the thread.

上一篇中向您展示了如何定义一个管理线程池以及在线程池上运行任务的类,这一篇将向您展示如何在一个线程池中运行任务。为了做到这一点,你需要将任务添加到线程池的工作队列中。当一个线程可用时,ThreadPoolExecutor会从队列中取出一个任务,并在线程上运行。

This lesson also shows you how to stop a task that's running. You might want to do this if a task starts, but then discovers that its work isn't necessary. Rather than wasting processor time, you can cancel the thread the task is running on. For example, if you are downloading images from the network and using a cache, you probably want to stop a task if it detects that an image is already present in the cache. Depending on how you write your app, you may not be able to detect this before you start the download.

这篇文章页向您展示如何停止一个正在运行的任务。这种情况是存在的,比如你启动了一个任务,后来发现这个任务不是必须的。为了节约处理器资源,你可以取消正在运行任务的线程。比如,如果你正在从网上下载一个图片,而且正在使用一个缓存,你忽然发现在缓存中已经有相同的图片了,此时你需要取消那个正在下载图片的任务。可能到你在下载这个图片之前,你都不知道在缓存中已经有相同的图片了。

Run a Task on a Thread in the Thread Pool


To start a task object on a thread in a particular thread pool, pass the Runnable to ThreadPoolExecutor.execute(). This call adds the task to the thread pool's work queue. When an idle thread becomes available, the manager takes the task that has been waiting the longest and runs it on the thread:

为了在一个线程池中开启一个任务,你只需传递runnable对象给 ThreadPoolExecutor.execute()即可。这个方法会将任务添加到线程池的工作队列。当线程池中有一个可用的线程时,ThreadPoolExecutor会选出一个等待时间最长的任务,交给这个可用的线程执行。

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

  

When ThreadPoolExecutor starts a Runnable on a thread, it automatically calls the object's run() method。

ThreadPoolExecutor将runnable对象交给一个线程执行的时候,runnable对象的run方法会自定被调用。

Interrupt Running Code


To stop a task, you need to interrupt the task's thread. To prepare to do this, you need to store a handle to the task's thread when you create the task. For example:

为了停止一个正在运行的任务,你需要打断运行这个任务的线程。为了做到这一点,当初在创建任务时,你应该存储一个该线程的句柄。比如:

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

  

To interrupt a thread, call Thread.interrupt(). Notice that Thread objects are controlled by the system, which can modify them outside of your app's process. For this reason, you need to lock access on a thread before you interrupt it, by placing the access in a synchronized block. For example:

为了能够取消一个线程,调用 Thread.interrupt()。请注意,线程是由系统来控制的,系统在你的应用的进程之外都能控制线程。正式如此,在你取消一个线程之前,一定锁住这个线程,锁住的方法就是将对这个线程的访问放在synchronized语句块中,例如:

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

  In most cases, Thread.interrupt() stops the thread immediately. However, it only stops threads that are waiting, and will not interrupt CPU or network-intensive tasks. To avoid slowing down or locking up the system, you should test for any pending interrupt requests before
attempting an operation :

在大多数的情况下, 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);
...

  

Running Code on a Thread Pool Thread_翻译的更多相关文章

  1. The CLR's Thread Pool

    We were unable to locate this content in zh-cn. Here is the same content in en-us. .NET The CLR's Th ...

  2. Improve Scalability With New Thread Pool APIs

    Pooled Threads Improve Scalability With New Thread Pool APIs Robert Saccone Portions of this article ...

  3. Communicating with the UI Thread_翻译

    In the previous lesson you learned how to start a task on a thread managed by ThreadPoolExecutor. Th ...

  4. MySQL thread pool【转】

    本文来自:http://blog.chinaunix.net/uid-26896862-id-3993773.html 刚刚经历了淘宝的双11,真实感受到了紧张的氛围.尽管DB淡定的度过,但是历程中的 ...

  5. CLR thread pool

    Thread Pooling https://msdn.microsoft.com/en-us/library/windows/desktop/ms686756(v=vs.85).aspx Threa ...

  6. MySQL Thread Pool: Problem Definition

    A new thread pool plugin is now a part of the MySQL Enterprise Edition.In this blog we will cover th ...

  7. ThreadPoolExecutor – Java Thread Pool Example

    https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice   Java t ...

  8. The threads in the thread pool will process the requests on the connections concurrently.

    https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html Most of the executor implem ...

  9. ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)

    Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...

随机推荐

  1. C#图片旋转

    这里以Bitmap为例说明问题. 可以看到,旋转方法需要传入一个参数,而这个参数是一个枚举类型,RotateFlipType. 系统提供了两大类型的旋转, 1.旋转后不翻转. 2.旋转后接着翻转.翻转 ...

  2. FMX有两种消息处理的实现方式,一种是用TMessageManager来实现自定义的消息,另外一种象TEdit中的实现,直接声明消息方法(firemonkey messaging)

    看FMX代码,发现有两种消息处理的实现方式,一种是用TMessageManager来实现自定义的消息,另外一种象TEdit中的实现,直接声明消息方法.   早前,看过文章说TMessageManage ...

  3. UbuntuServer添加软件源列表

    要使用Ubuntu前,我们一般都要先做好工具!特别是对于安装这一块~~~~ 1.配置前,先做个配置文件的备份: $sudo cp /etc/apt/sources.list /etc/apt/sour ...

  4. [2017.02.21-22] 《Haskell趣学指南 —— Learning You a Haskell for Great Good!》

    {- 2017.02.21-22 <Haskell趣学指南 -- Learning You a Haskell for Great Good!> 学习了Haskell的基本语法,并实现了一 ...

  5. postgres数据库小记

    因为工作中需要查询其他部门数据库,刚好是postgres数据库,用python链接的话,可以用psycopg2库,具体用法其实和MysqlDB是一样的,就是安装的时候遇到点问题. 安装的时候,提示: ...

  6. MYSQL的全局变量和会话变量

    系统变量又分为全局变量与会话变量. 全局变量在MYSQL启动的时候由服务器自动将它们初始化为默认值,这些默认值可以通过更改my.ini这个文件来更改. 会话变量在每次建立一个新的连接的时候,由MYSQ ...

  7. ZooKeeper学习之路(五)—— ACL权限控制

    一.前言 为了避免存储在Zookeeper上的数据被其他程序或者人为误修改,Zookeeper提供了ACL(Access Control Lists)进行权限控制.只有拥有对应权限的用户才可以对节点进 ...

  8. 关于AI本质的思考

    前言 最近几天和一位朋友探讨了一下现阶段的人工智能以及未来发展,并且仔细重读了尤瓦尔赫拉利的“简史三部曲”,产生了一些关于AI的新想法,觉得有必要整理出来. 程序.AI的本质 现代的计算机都是基于图灵 ...

  9. jQuery入门——注册事件

    下面举例介绍注册事件的几种方法: 以光棒效果为例 1.bind注册: <!DOCTYPE html> <html> <head> <meta charset= ...

  10. JavaScript 事件(捕获和冒泡 兼容性写法)

    事件    浏览器客户端上客户触发的行为都称为事件 所有的事件都是天生自带的 不需要人为绑定 只需要我们去触发通过obj.事件名=function(){} 我们给元素的事件绑定了一个方法 事件名:on ...