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. oracle获取字符串长度函数length()和lengthb()

    oracle获取字符串长度函数length()和lengthb()   lengthb(string)计算string所占的字节长度:返回字符串的长度,单位是字节 length(string)计算st ...

  2. Linux bash介绍与使用

    Linux————bash的简单使用 对于一个操作系统来说,shell相当于内核kernel外的一层外壳,作为用户接口.一般来说,操作系统的接口分为两类:CLI:command line interf ...

  3. git 删除目录

    1. 查看本地已经被删除的文件 2. 删除 目录以及目录下的文件 [root@test01 h2_mopub_replace]# git rm ../test_code_driver -r 3. [r ...

  4. PyTorch 60 分钟入门教程

    PyTorch 60 分钟入门教程:PyTorch 深度学习官方入门中文教程 http://pytorchchina.com/2018/06/25/what-is-pytorch/ PyTorch 6 ...

  5. linux输入yum后提示: -bash: /usr/bin/yum: No such file or directory的解决方案

    linux输入yum后提示: -bash: /usr/bin/yum: No such file or directory的解决方案 今天在安装程序时,发现有一个插件未安装,我就随手敲了一个命令,看都 ...

  6. maximize_window fullscreen_window minimize_window

    # Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreemen ...

  7. solr 命令

    本文为转载内容:源地址:http://blog.csdn.net/matthewei6/article/details/50620600 查看帮助 bin/solr -help            ...

  8. YTU 2435: C++ 习题 输出日期时间--友元函数

    2435: C++ 习题 输出日期时间--友元函数 时间限制: 1 Sec  内存限制: 128 MB 提交: 1069  解决: 787 题目描述 设计一个日期类和时间类,编写display函数用于 ...

  9. svn回到历史的某个版本

    svn回到历史的某个版本 分类: linux大类2011-08-05 10:25 7468人阅读 评论(0) 收藏 举报 svntortoisesvn svn回到历史的某个版本在代码的编写过程中,难免 ...

  10. HDU1402:A * B Problem Plus(FFT与大数乘法)

    Calculate A * B. Input Each line will contain two integers A and B. Process to end of file. Note: th ...