Android 线程池系列教程(4) 启动线程池中的线程和中止池中线程
1.This lesson teaches you to
2.You should also read
3.Try it out
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, theThreadPoolExecutor
takes a task from the queue and runs it on the thread.
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.
4.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
toThreadPoolExecutor.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:
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.
5.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:
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 = ; 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 :
/*
* 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, , imageBuffer.length, bitmapOptions);
...
Android 线程池系列教程(4) 启动线程池中的线程和中止池中线程的更多相关文章
- 【转】Android总结篇系列:Activity启动模式(lauchMode)
[转]Android总结篇系列:Activity启动模式(lauchMode) 本来想针对Activity中的启动模式写篇文章的,后来网上发现有人已经总结的相当好了,在此直接引用过来,并加上自己的一些 ...
- Android性能优化系列之App启动优化
Android性能优化系列之布局优化 Android性能优化系列之内存优化 Android性能优化系列之apk瘦身 应用的启动速度缓慢是我们在开发过程中常常会遇到的问题,比方启动缓慢导致的黑屏.白屏问 ...
- Android总结篇系列:Activity启动模式(lauchMode)
本来想针对Activity中的启动模式写篇文章的,后来网上发现有人已经总结的相当好了,在此直接引用过来,并加上自己的一些理解,在此感谢原作者. 文章地址: http://blog.csdn.net/l ...
- Android 线程池系列教程(5)与UI线程通信要用Handler
Communicating with the UI Thread 上一课 下一课 1.This lesson teaches you to Define a Handler on the UI Thr ...
- Android 线程池系列教程(2)Thread,Runnable是基类及如何写Run方法
Specifying the Code to Run on a Thread 上一课 下一课 1.This lesson teaches you to Define a Class that Im ...
- Android 线程池系列教程(1)目录
Sending Operations to Multiple Threads 1.Dependencies and prerequisites Android 3.0 (API Level 11) o ...
- Android 线程池系列教程(3) 创建线程池
Creating a Manager for Multiple Threads 上一课 下一课 1.This lesson teaches you to Define the Thread Pool ...
- 跨平台移动开发phonegap/cordova 3.3全系列教程-app启动画面
1.app启动画面设计 用photoshop设计启动画面,图片分辨率为720*1280 保存的文件名为splash.png 将splash.png复制到res\drawable,如图 PS:要先添加闪 ...
- FL studio系列教程(十四):如何在FL Studio播放列表中排列样式
我们在FL Studio中做好了节奏样式后就可以在播放列表窗口中进行乐曲的编排了.刚接触这款软件的同学肯定会对如何编排比较陌生但也比较憧憬的,因为它是从一个窗口到另一个窗口中的操作.其实明白了这里的知 ...
随机推荐
- StringUtil内部方法差异
StringUtil 的 isBlank.isEmply.isNotEmpty.isNotBlank 区别 String.trim()方法: trim()是去掉首尾空格 append(Stri ...
- Centos5设置静态IP地址
1.设置静态IP地址,修改/etc/sysconfig/network-scripts/ifcfg-eth0的内容: DEVICE=eth0 #网卡对应的设备别名 BOOTPROTO=static # ...
- JS表格分页组件:fupage的设计思路和详细使用方法(未来考虑开源,争取在2015年)
一.背景 之前在秒针工作的时候,某js高级project师写了非常多自己的组件.当中一套是分页组件.叫做st-grid. 只是在我看来,bug太多.我常常给他反馈bug,我也不清楚为啥 ...
- NS3网络仿真(12): ICMPv4协议
快乐虾 http://blog.csdn.net/lights_joy/ 欢迎转载,但请保留作者信息 ICMP的全称是 Internet ControlMessage Protocol . 其目的就是 ...
- 【iOS系列】-oc中特有的语法
[iOS系列]-oc中特有的语法 oc数据类型: 1,基本类型 2,对象类型 3,id 4,BOOL 5,block 6,SEL 1:category 使用继承关系来扩充一个类,有一个弊病,高耦合性 ...
- win7 32位下安装MySQL出现的---1067系统错误---问题及解决
每次安装数据库,总是出现这样那样的问题.如今记录下来,供日后參考咯.... 下载的是解压缩-zip版本号的.安装配置教程參照洪哥笔记文章-<MySQL-5.6.13解压版(zip版)安装配置教程 ...
- autofac如何注册静态方法里的接口对象
标题可能是不准确的,因为我不知道如何描述.不知道的原因,是对依赖注入一知半解. Autofac可以自动注册对象实例到接口,人所尽知.而在asp.net mvc中,这个实例化的工作,通常在每个控制器的构 ...
- ubuntu字符界面下显示中文和调整分辨率
1.sudo apt-get install zhcon 2.vi /etc/zhcon.conf 修改下面两行 x_resolution 1024 y_resolution 768 完成这两步后在 ...
- MySQL之——server保持与MySQL的连接
转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47008019 server程序常常要訪问数据库,而且server程序是长时间保持运 ...
- RMQ(Range Minimum Query)问题(转)
问题描述 RMQ问题是求给定区间中的最值问题.对于长度为n的数列A,回答若干查询RMQ(A, i, j).返回数组A中下标在[i,j]里的最小值的下标. 比如数列 5,8,1,3,6,4,9,5,7 ...