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中做好了节奏样式后就可以在播放列表窗口中进行乐曲的编排了.刚接触这款软件的同学肯定会对如何编排比较陌生但也比较憧憬的,因为它是从一个窗口到另一个窗口中的操作.其实明白了这里的知 ...
随机推荐
- Centos7 Samba 独立账户
创建了一个组:smbgrp 和用户srijan通过认证来访问Samba服务器. groupadd smbgrp useradd srijan -G smbgrp smbpasswd -a srijan ...
- Office WORD如何为每一页设置不同的页眉页脚
如下图所示,我想要为封面和目录,摘要等等设置不同的页眉页脚(一般封面和目录不需要页脚) 而从正文开始,套用相同的页眉和以页数作为页脚(注意"第一章 绪论"不是这个文档的第一页) ...
- activiti自己定义流程之自己定义表单(二):创建表单
注:环境配置:activiti自己定义流程之自己定义表单(一):环境配置 在上一节自己定义表单环境搭建好以后,我就正式開始尝试自己创建表单,在后台的处理就比較常规,主要是针对ueditor插件的功能在 ...
- mysql字段A复制到字段B,并替换指定字符
',字段a); eg:update `hy_b_pro` set goldWeight=jinJinZhong;
- ABP框架 - 介绍 VS2017调试器无法附加到IIS进程(w3wp.exe) c# 动态实例化一个泛型类
ABP框架 - 介绍 在14,15年间带领几个不同的团队,交付了几个项目,在这个过程中,虽然几个项目的业务不一样,但是很多应用程序架构基础性的功能却是大同小异,例如认证.授权.请求验证.异常处理. ...
- 项目实战之玩转div+css制作自己定义形状
项目需求 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/diss ...
- Android-support-v4源码查看
- Linux文档,目录命令
1,Linux文件系统结构 Linux目录结构的组织形式和Windows有很大的不同,首先Linux没有"盘(C盘,D盘,E盘的概念)"的概念,已经建立文件系统的硬盘分区被挂载到某 ...
- HDU1540 Tunnel Warfare —— 线段树 区间合并
题目链接:https://vjudge.net/problem/HDU-1540 uring the War of Resistance Against Japan, tunnel warfare w ...
- YTU 2958: 代码填充--雨昕学画画
2958: 代码填充--雨昕学画画 时间限制: 1 Sec 内存限制: 128 MB 提交: 156 解决: 102 题目描述 雨昕开始学画水彩画,老师给雨昕一个形状(Shape)类,雨昕在Sha ...