Android 线程池系列教程(4) 启动线程池中的线程和中止池中线程

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:

复制代码
 1 public class PhotoManager {
 2     public void handleState(PhotoTask photoTask, int state) {
 3         switch (state) {
 4             // The task finished downloading the image
 5             case DOWNLOAD_COMPLETE:
 6             // Decodes the image
 7                 mDecodeThreadPool.execute(
 8                         photoTask.getPhotoDecodeRunnable());
 9             ...
10         }
11         ...
12     }
13     ...
14 }
复制代码

  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:

复制代码
 1 class PhotoDecodeRunnable implements Runnable {
 2     // Defines the code to run for this task
 3     public void run() {
 4         /*
 5          * Stores the current Thread in the
 6          * object that contains PhotoDecodeRunnable
 7          */
 8         mPhotoTask.setImageDecodeThread(Thread.currentThread());
 9         ...
10     }
11     ...
12 }
复制代码

  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:

复制代码
 1 public class PhotoManager {
 2     public static void cancelAll() {
 3         /*
 4          * Creates an array of Runnables that's the same size as the
 5          * thread pool work queue
 6          */
 7         Runnable[] runnableArray = new Runnable[mDecodeWorkQueue.size()];
 8         // Populates the array with the Runnables in the queue
 9         mDecodeWorkQueue.toArray(runnableArray);
10         // Stores the array length in order to iterate over the array
11         int len = runnableArray.length;
12         /*
13          * Iterates over the array of Runnables and interrupts each one's Thread.
14          */
15         synchronized (sInstance) {
16             // Iterates over the array of tasks
17             for (int runnableIndex = 0; runnableIndex < len; runnableIndex++) {
18                 // Gets the current thread
19                 Thread thread = runnableArray[taskArrayIndex].mThread;
20                 // if the Thread exists, post an interrupt to it
21                 if (null != thread) {
22                     thread.interrupt();
23                 }
24             }
25         }
26     }
27     ...
28 }
复制代码

  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 :

复制代码
 1 /*
 2  * Before continuing, checks to see that the Thread hasn't
 3  * been interrupted
 4  */
 5 if (Thread.interrupted()) {
 6     return;
 7 }
 8 ...
 9 // Decodes a byte array into a Bitmap (CPU-intensive)
10 BitmapFactory.decodeByteArray(
11         imageBuffer, 0, imageBuffer.length, bitmapOptions);
12 ...
复制代码

 

 

posted @   f9q  阅读(540)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示