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. delphi中使用词霸2005的动态库XdictGrb.dll实现屏幕取词

    近日来,在网上发现关于屏幕取词技术的捷径,搜索很长时间,发现实现方式以VB出现的居多,但是通过Delphi来实现的却好象没有看到,自己参考着VB的相关代码琢磨了一下通过delphi来实现的方式. 其实 ...

  2. Qt 事件处理 快捷键(重写eventFilter的函数,使用Qt::ControlModifier判断)

    CTRL+Enter发送信息的实现 在现在的即时聊天程序中,一般都设置有快捷键来实现一些常用的功能,类似QQ可以用CTRL+Enter来实现信息的发送. 在QT4中,所有的事件都继承与QEvent这个 ...

  3. 如何计算memcache的容量

    在容量足够的情况下,当然是越大越好,但这样会造成浪费.不考虑这种情况.我们一般的情况是: memcache集群一开始创建会根据存储的数据量与访问量进行容量大小的估算.再算一个20%的冗余. 在网站快速 ...

  4. Maven 安装和使用

    Maven 安装和使用 1.下载 http://maven.apache.org/download.cgi 2.tar -bin.tar.gz 3.环境变量 /etc/profile export M ...

  5. Qt 中C++ static_cast 和 reinterpret_cast的区别(static_cast是隐式类型转换,会有数据损失,reinterpret_cast是底层二进制转换,没有数据损失)

    1.C++中的static_cast执行非多态的转换,用于代替C中通常的转换操作.因此,被做为隐式类型转换使用.比如: int i; float f = 166.7f; i = static_cast ...

  6. 关于Qt 5-MSVC 2015 64位在 win7 64位系统debug程序崩溃的问题

     关于Qt 5-MSVC 2015 64位在 win7 64位系统debug程序崩溃的问题 在win7 64位系统安装VC2015的编译器,并安装了 Qt 5.6 -5.7 VC2015 64位版本测 ...

  7. 【Webkit Blog翻译】深入研究WebRTC | 内有福利

    本文译自 A Closer Look Into WebRTC” 我们在最近的一篇 WebKit博客中宣布了对High Sierra平台和iOS中Safari的WebRTC支持.现在,我们希望能够带领大 ...

  8. Java8新特性——lambda表达式.(案例:词频统计)

    需求:读入一个文本文件,确定所有单词的使用频率并从高到低排序,打印出所有单词及其频率的排序列表 先用传统方法解: package cn._1.wordfrequency; import java.ut ...

  9. Vue SSR初探

    因为之前用nuxt开发过应用程序,但是nuxt早就达到了开箱即用的目的,所以一直对vue ssr的具体实现存在好奇. 构建步骤 我们通过上图可以看到,vue ssr 也是离不开 webpack 的打包 ...

  10. 如何使用JavaScript导入和导出Excel文件

    本文由葡萄城技术团队于原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. JavaScript是一个涵盖多种框架.直译式.可以轻松自定义客户端的脚本 ...