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中做好了节奏样式后就可以在播放列表窗口中进行乐曲的编排了.刚接触这款软件的同学肯定会对如何编排比较陌生但也比较憧憬的,因为它是从一个窗口到另一个窗口中的操作.其实明白了这里的知 ...
随机推荐
- 剑指Offer面试题15(Java版):链表中倒数第K个结点
题目: 输入一个链表.输出该链表中倒数第k哥结点. 为了符合大多数人的习惯,本题从1開始计数.即链表的尾结点是倒数第1个结点. 比如一个链表有6个结点.从头结点開始它们的值依次是1.2.3,4,5, ...
- 三. 200多万元得到的创业教训--创业并不须要app
摘要:有个点子,研发app或站点,推广,不断改进,探索盈利模式.这个通用的移动互联网创业流程.但我觉得.在某些特定的商业模式下,"研发app或站点"这步能够砍掉或推迟. 健生干货分 ...
- 【iOS系列】-A server with the specified hostname could not be found.问题解决
[iOS系列]-A server with the specified hostname could not be found.问题解决 Reveal 在iOS开发中可以方便查看界面的布局,较为方便的 ...
- hdu 4925 Apple Tree--2014 Multi-University Training Contest 6
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4925 Apple Tree Time Limit: 2000/1000 MS (Java/Others ...
- HDU 5274 Dylans loves tree 树链剖分+线段树
Dylans loves tree Problem Description Dylans is given a tree with N nodes. All nodes have a value A[ ...
- python iterable 和list、dictionary的区别和联系
1 为什么一些函数的参数指定要iterable object的,但是也可以传入list为参数? 因为list.dictionary都是iterable object. 在iterable object ...
- ios app抓包分析
1 使用rvictl工具 这是mac下的一条命令.ios usb连mac,然后创建虚拟网络接口. 2 使用wireshark抓包 wireshark可以抓这个虚拟网络接口上的数据包.
- windows安装SVN服务器并设置开机启动
1.安装SVN服务器,到http://subversion.apache.org/packages.html上下载windows版的SVN,并安装,在命令行下运行svn命令,如下所以,则svn服务器安 ...
- android编译openssl静态库.a
github上有一个开源项目,已经为你编译openssl建好了工程. 地址:https://github.com/aluvalasuman/OpenSSL1.0.1cForAndroid 选择需要的版 ...
- Ubuntu下Jupyter Notebook的安装
pip install --upgrade pip //更新pip pip install jupyter sudo apt install jupyter-notebook 运行 jupyter-n ...