Running Code on a Thread Pool Thread

1.This lesson teaches you to

  1. Run a Runnable on a Thread in the Thread Pool
  2. Interrupt Running Code

2.You should also read

3.Try it out

  DOWNLOAD THE SAMPLE  ThreadSample.zip

  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) 启动线程池中的线程和中止池中线程的更多相关文章

  1. 【转】Android总结篇系列:Activity启动模式(lauchMode)

    [转]Android总结篇系列:Activity启动模式(lauchMode) 本来想针对Activity中的启动模式写篇文章的,后来网上发现有人已经总结的相当好了,在此直接引用过来,并加上自己的一些 ...

  2. Android性能优化系列之App启动优化

    Android性能优化系列之布局优化 Android性能优化系列之内存优化 Android性能优化系列之apk瘦身 应用的启动速度缓慢是我们在开发过程中常常会遇到的问题,比方启动缓慢导致的黑屏.白屏问 ...

  3. Android总结篇系列:Activity启动模式(lauchMode)

    本来想针对Activity中的启动模式写篇文章的,后来网上发现有人已经总结的相当好了,在此直接引用过来,并加上自己的一些理解,在此感谢原作者. 文章地址: http://blog.csdn.net/l ...

  4. Android 线程池系列教程(5)与UI线程通信要用Handler

    Communicating with the UI Thread 上一课 下一课 1.This lesson teaches you to Define a Handler on the UI Thr ...

  5. Android 线程池系列教程(2)Thread,Runnable是基类及如何写Run方法

    Specifying the Code to Run on a Thread 上一课   下一课 1.This lesson teaches you to Define a Class that Im ...

  6. Android 线程池系列教程(1)目录

    Sending Operations to Multiple Threads 1.Dependencies and prerequisites Android 3.0 (API Level 11) o ...

  7. Android 线程池系列教程(3) 创建线程池

    Creating a Manager for Multiple Threads 上一课  下一课 1.This lesson teaches you to Define the Thread Pool ...

  8. 跨平台移动开发phonegap/cordova 3.3全系列教程-app启动画面

    1.app启动画面设计 用photoshop设计启动画面,图片分辨率为720*1280 保存的文件名为splash.png 将splash.png复制到res\drawable,如图 PS:要先添加闪 ...

  9. FL studio系列教程(十四):如何在FL Studio播放列表中排列样式

    我们在FL Studio中做好了节奏样式后就可以在播放列表窗口中进行乐曲的编排了.刚接触这款软件的同学肯定会对如何编排比较陌生但也比较憧憬的,因为它是从一个窗口到另一个窗口中的操作.其实明白了这里的知 ...

随机推荐

  1. Centos 6.x 安装Nagios及WEB管理nagiosql实现windows及linux监控指南

    一.Nagios简介 Nagios是一款开源的电脑系统和网络监视工具,能有效监控Windows.Linux和Unix的主机状态,交换机路由器等网络设置,打印机等.在系统或服务状态异常时发出邮件或短信报 ...

  2. Mybatis加入Ehcache支持

    1.Mybatis默认的缓存配置 MyBatis 包括一个很强大的查询缓存特性,它能够很方便地配置和定制. Mybatis缓存包括全局的缓存和局部的缓存.全局的缓存能够讲主配置文件的setting属性 ...

  3. Got error: 1449: The user specified as a definer ('root'@'%') does not exist when using LOCK TAB

    在linux下,用mysql的导出语句: mysqldump -hlocalhost -uroot -pPasswd table >/home/ftp/test.sql 出现了 mysqldum ...

  4. MyEclipse搭建SSH(Struts2+Spring2+Hibernate3)框架项目教程

    对Struts.spring.hibernate大体上了解一遍后,就是针对这个几个框架的整合了. 怎样整合,请看以下: 第一:Struts2的jar和xml配置文件: jar包: commons-fi ...

  5. centos7 安装配置openstack-dashboard (官网openstack-juno版)

    感谢朋友支持本博客.欢迎共同探讨交流.因为能力和时间有限.错误之处在所难免.欢迎指正! 假设转载.请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...

  6. Java 中 泛型的限定

         泛型 一般 出如今集合中,迭代器中 也会出现!      泛型 是为了 提高代码的 安全性. 泛型 确保数据类型的唯一性. 在我们经常使用的容器中.  越是 单一 约优点理啊!       ...

  7. DBscan算法及其Python实现

    DBSCAN简介: 1.简介 DBSCAN 算法是一种基于密度的空间聚类算法.该算法利用基于密度的聚类的概念,即要求聚类空间中的一定区域内所包含对象(点或其它空间对象)的数目不小于某一给定阀值.DBS ...

  8. ZOJ 3691 Flower(最大流+二分)

    Flower Time Limit: 8 Seconds      Memory Limit: 65536 KB      Special Judge Gao and his girlfriend's ...

  9. flask的路由配置,特殊装饰器

    1,flask中的路由 endpoint-url_for反向地址 endpoint默认是视图函数名endpoint="雪雪" methods 指定视图函数的请求方式,默认GET d ...

  10. Codeforces Round #261 (Div. 2)——Pashmak and Graph

    题目链接 题意: n个点.m个边的有向图.每条边有一个权值,求一条最长的路径,使得路径上边值严格递增.输出路径长度 )) 分析: 由于路径上会有反复点,而边不会反复.所以最開始想的是以边为状态进行DP ...