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中做好了节奏样式后就可以在播放列表窗口中进行乐曲的编排了.刚接触这款软件的同学肯定会对如何编排比较陌生但也比较憧憬的,因为它是从一个窗口到另一个窗口中的操作.其实明白了这里的知 ...
随机推荐
- 改动Android启动画面
一.Android的启动步骤 1.启动Linux 2.载入Android 3.显示Android桌面 二.分析 Android载入开机动画的源代码文件是: /opt/android4.3/framew ...
- 五分钟搭建 Flash 视频直播站
想在家里对全世界直播网络视频节目吗?如今视频网站是多如牛毛,但能让你玩直播的估计没几个吧?看完这篇教程就能帮你实现网络主持人的梦想.不花钱,不懂编程,不用写代码也行哦~ 首先是最低机器要求:Windo ...
- 把A表中的a字段和b字段数据 复制到B表中的aa字段和bb字段
insert into tab2 (column1,column2) select column1,column2 from tab1
- 2016/2/26 <marquee></marquee>实现多种滚动效果
页面的自动滚动效果,可由javascript来实现,但是有一个html标签 - <marquee></marquee>可以实现多种滚动效果,无需js控制.使用marquee标记 ...
- Koa2学习(六)使用koa-router
Koa2学习(六)使用koa-router 配置简单路由 引入中间件 配置需要的路由 通过app.use注册路由 const Koa = require('koa') const app = new ...
- 内存转储文件 Memory.dmp
https://baike.sogou.com/v63435711.htm?fromTitle=内存转存文件 内存转储是用于系统崩溃时,将内存中的数据转储保存在转储文件中,供给有关人员进行排错分析用途 ...
- YTU 2432: C++习题 对象数组输入与输出
2432: C++习题 对象数组输入与输出 时间限制: 1 Sec 内存限制: 128 MB 提交: 1603 解决: 1152 题目描述 建立一个对象数组,内放n(n<10)个学生的数据( ...
- AppCompatActivity、ActionBarActivity、FragmentActivity和Activity的区别
package com.chy.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bu ...
- 【繁琐工作自动化】pandas 处理 excel 文件
0. 一般处理 读取 excel 格式文件:df = pd.read_excel('xx.xlsx'),下面是一些简单查看文件内容的函数: df.head():展示前五行: df.columns:展示 ...
- I.MX6 简单电路模拟USB设备的插入
/**************************************************************************** * I.MX6 简单电路模拟USB设备的插入 ...