Running Code on a Thread Pool Thread_翻译
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_翻译的更多相关文章
- 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 ...
- Improve Scalability With New Thread Pool APIs
Pooled Threads Improve Scalability With New Thread Pool APIs Robert Saccone Portions of this article ...
- Communicating with the UI Thread_翻译
In the previous lesson you learned how to start a task on a thread managed by ThreadPoolExecutor. Th ...
- MySQL thread pool【转】
本文来自:http://blog.chinaunix.net/uid-26896862-id-3993773.html 刚刚经历了淘宝的双11,真实感受到了紧张的氛围.尽管DB淡定的度过,但是历程中的 ...
- CLR thread pool
Thread Pooling https://msdn.microsoft.com/en-us/library/windows/desktop/ms686756(v=vs.85).aspx Threa ...
- 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 ...
- ThreadPoolExecutor – Java Thread Pool Example
https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice Java t ...
- 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 ...
- ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...
随机推荐
- UWP开发-在UWP中使用sqlite
原文:UWP开发-在UWP中使用sqlite sqlite是一种轻量级的数据库,对于一些资源紧张又需要数据库的开发非常好用. SQLite 是一个开源的无服务器嵌入式数据库. 这些年来,它已作为面向存 ...
- Globalize 1.0 发布,jQuery 的国际化插件
分享 <关于我> 分享 [中文纪录片]互联网时代 http://pan.baidu.com/s/1qWkJfcS 分享 <HTML开发MacOSAp ...
- Bamboo 0.2.11 发布,HAProxy 自动配置
Bamboo 0.2.11 发布,此版本更新内容如下: 新特性 提供更多的模板字符串函数:strings.Split, strings.Join,strings.Replace, strings.T ...
- linux下编译qt5.6.0静态库(使用./configure --help来看看都有哪些参数。超详细,有每一个模块的说明。如果改变了安装的目录,需要到安装目录下的bin目录下创建文件qt.conf)(乌合之众)good
linux下编译qt5.6.0静态库 linux下编译qt5.6.0静态库 configure生成makefile 安装选项 Configure选项 第三方库: 附加选项: QNX/Blackberr ...
- Centos7安装Mysql-最方便、最快捷
你想在Linux操作系统安装Mysql?你不想去官网下载再复制?,那就来看看我的方案,简单.快捷轻松安装.使用. 首先,检查安装情况 1.查看有没有安装过: yum ...
- 利用Rsync同步工具上传、删除目标文件
Rsync是文件备份工具,当然也可以当做传输工具,管理远程服务器的文件 上传 rsync -avzP --progress --port 9106 /path/.../指定文件 root@192.16 ...
- xmanager小技巧
使用manager时候,左键选中之后,直接右键粘贴,能带来效率的提升.虽然是小技巧,但有人还是不知道,这里简单写一下,供需要的同学参考. 简单二步设置: 1.工具-选项
- Tido 习题-二叉树-树状数组实现
题目描述 这就是一个简单的树状数组入门题 可以动态地进行区间和查询 随时可能会进行更新 #include<iostream> #include<cstdio> #inclu ...
- Django的的安装和配置
1. 下载 1. 命令行 pip install django==1.11.18 -i https://pypi.douban.com/simple/ 2. 创建项目 1. 命令行 django-ad ...
- 前后端开发(2):浏览器与PHP程序的交互
上一节介绍怎么在mac电脑上启用PHP程序,并且演示了一个简单的例子,这个例子运行时,涉及了浏览器.apache以及PHP程序的交互,这三者的关系大概是这样的: 一般来说,浏览器(或者类似功能的程序) ...