Creating a Manager for Multiple Threads

1.This lesson teaches you to

  1. Define the Thread Pool Class
  2. Determine the Thread Pool Parameters
  3. Create a Pool of Threads

2.You should also read

3. Try it out

  DOWNLOAD THE SAMPLE ThreadSample.zip

  The previous lesson showed how to define a task that executes on a separate thread. If you only want to run the task once, this may be all you need. If you want to run a task repeatedly on different sets of data, but you only need one execution running at a time, anIntentService suits your needs. To automatically run tasks as resources become available, or to allow multiple tasks to run at the same time (or both), you need to provide a managed collection of threads. To do this, use an instance of ThreadPoolExecutor, which runs a task from a queue when a thread in its pool becomes free. To run a task, all you have to do is add it to the queue.

  A thread pool can run multiple parallel instances of a task, so you should ensure that your code is thread-safe. Enclose variables that can be accessed by more than one thread in asynchronized block. This approach will prevent one thread from reading the variable while another is writing to it. Typically, this situation arises with static variables, but it also occurs in any object that is only instantiated once. To learn more about this, read the Processes and Threads API guide.

4.Define the Thread Pool Class

  Instantiate ThreadPoolExecutor in its own class. Within this class, do the following:

Use static variables for thread pools
  You may only want a single instance of a thread pool for your app, in order to have a single control point for restricted CPU or network resources. If you have different Runnable types, you may want to have a thread pool for each one, but each of these can be a single instance. For example, you can add this as part of your global field declarations:
     public class PhotoManager {
...
static {
...
// Creates a single static instance of PhotoManager
sInstance = new PhotoManager();
}
...
Use a private constructor
  Making the constructor private ensures that it is a singleton, which means that you don't have to enclose accesses to the class in a synchronized block:
     public class PhotoManager {
...
/**
* Constructs the work queues and thread pools used to download
* and decode images. Because the constructor is marked private,
* it's unavailable to other classes, even in the same package.
*/
private PhotoManager() {
...
}
Start your tasks by calling methods in the thread pool class.
  Define a method in the thread pool class that adds a task to a thread pool's queue. For example:
     public class PhotoManager {
...
// Called by the PhotoView to get a photo
static public PhotoTask startDownload(
PhotoView imageView,
boolean cacheFlag) {
...
// Adds a download task to the thread pool for execution
sInstance.
mDownloadThreadPool.
execute(downloadTask.getHTTPDownloadRunnable());
...
}
Instantiate a Handler in the constructor and attach it to your app's UI thread.
  A Handler allows your app to safely call the methods of UI objects such as View objects. Most UI objects may only be safely altered from the UI thread. This approach is described in more detail in the lesson Communicate with the UI Thread. For example: 
      private PhotoManager() {
...
// Defines a Handler object that's attached to the UI thread
mHandler = new Handler(Looper.getMainLooper()) {
/*
* handleMessage() defines the operations to perform when
* the Handler receives a new Message to process.
*/
@Override
public void handleMessage(Message inputMessage) {
...
}
...
}
}

5.Determine the Thread Pool Parameters

  Once you have the overall class structure, you can start defining the thread pool. To instantiate aThreadPoolExecutor object, you need the following values:

Initial pool size and maximum pool size
  The initial number of threads to allocate to the pool, and the maximum allowable number. The number of threads you can have in a thread pool depends primarily on the number of cores available for your device. This number is available from the system environment:
 public class PhotoManager {
...
/*
* Gets the number of available cores
* (not always the same as the maximum number of cores)
*/
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
}
This number may not reflect the number of physical cores in the device; some devices have CPUs that deactivate one or more cores depending on the system load. For these devices,availableProcessors() returns the number of active cores, which may be less than the total number of cores.
Keep alive time and time unit
  The duration that a thread will remain idle before it shuts down. The duration is interpreted by the time unit value, one of the constants defined in TimeUnit.
A queue of tasks
  The incoming queue from which ThreadPoolExecutor takes Runnable objects. To start code on a thread, a thread pool manager takes a Runnable object from a first-in, first-out queue and attaches it to the thread. You provide this queue object when you create the thread pool, using any queue class that implements the BlockingQueue interface. To match the requirements of your app, you can choose from the available queue implementations; to learn more about them, see the class overview forThreadPoolExecutor. This example uses the LinkedBlockingQueue class:
 public class PhotoManager {
...
private PhotoManager() {
...
// A queue of Runnables
private final BlockingQueue<Runnable> mDecodeWorkQueue;
...
// Instantiates the queue of Runnables as a LinkedBlockingQueue
mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>();
...
}
...
}

6.Create a Pool of Threads

  To create a pool of threads, instantiate a thread pool manager by calling ThreadPoolExecutor(). This creates and manages a constrained group of threads. Because the initial pool size and the maximum pool size are the same, ThreadPoolExecutor creates all of the thread objects when it is instantiated. For example:

     private PhotoManager() {
...
// Sets the amount of time an idle thread waits before terminating
private static final int KEEP_ALIVE_TIME = ;
// Sets the Time Unit to seconds
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// Creates a thread pool manager
mDecodeThreadPool = new ThreadPoolExecutor(
NUMBER_OF_CORES, // Initial pool size
NUMBER_OF_CORES, // Max pool size
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
mDecodeWorkQueue);
}
 

Android 线程池系列教程(3) 创建线程池的更多相关文章

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

    Running Code on a Thread Pool Thread 上一课   下一课 1.This lesson teaches you to Run a Runnable on a Thre ...

  2. 线程池ThreadPoolExecutor分析: 线程池是什么时候创建线程的,队列中的任务是什么时候取出来的?

    带着几个问题进入源码分析: 1. 线程池是什么时候创建线程的? 2. 任务runnable task是先放到core到maxThread之间的线程,还是先放到队列? 3. 队列中的任务是什么时候取出来 ...

  3. Java并发——ThreadPoolExecutor线程池解析及Executor创建线程常见四种方式

    前言: 在刚学Java并发的时候基本上第一个demo都会写new Thread来创建线程.但是随着学的深入之后发现基本上都是使用线程池来直接获取线程.那么为什么会有这样的情况发生呢? new Thre ...

  4. Mysql线程池系列一:什么是线程池和连接池( thread_pool 和 connection_pool)

       thread_pool 和 connection_pool 当客户端请求的数据量比较大的时候,使用线程池可以节约大量的系统资源,使得更多的CPU时间和内存可以高效地利用起来.而数据库连接池的使用 ...

  5. Spring Boot2 系列教程(二)创建 Spring Boot 项目的三种方式

    我最早是 2016 年底开始写 Spring Boot 相关的博客,当时使用的版本还是 1.4.x ,文章发表在 CSDN 上,阅读量最大的一篇有 43W+,如下图: 2017 年由于种种原因,就没有 ...

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

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

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

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

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

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

  9. [C# 线程处理系列]专题四:线程同步

    目录: 一.线程同步概述 二.线程同步的使用 三 .总结 一.线程同步概述 前面的文章都是讲创建多线程来实现让我们能够更好的响应应用程序,然而当我们创建了多个线程时,就存在多个线程同时访问一个共享的资 ...

随机推荐

  1. ITIL的考核管理体系

    是的,我们ITIL的考核管理体系,大概是从几个方面进行考核的.阿里巴巴作为一个上市公司,是全球的B2B电子商务的领先者,那么作为我们的运维部,保证完整的可用性是首当其冲的.我们的ITIL考核体系里面, ...

  2. [Javascript] Understanding the .constructor property on JavaScript Objects

    Constructor functions hold an interesting purpose in JavaScript. Unlike in classical languages, they ...

  3. Scrum 常见错误实践 之 形式化的站会

    站会作为一个团队最容易实施的敏捷实践,为广大team leader和老板们所喜欢,但大部分程序员却很抵触.其主要原因就是很多时候站会都流于形式,没能帮助团队成员解决问题.改进效率. 一种常见的情况就是 ...

  4. 在matlab中生成m序列

    实验环境为matlab2013b 1.首先编写一个mseq.m文件,内容为: function[mseq]=m_sequence(fbconnection)  n=length(fbconnectio ...

  5. 谈谈TensorFlow with CPU support or TensorFlow with GPU support(图文详解)

    不多说,直接上干货! You must choose one of the following types of TensorFlow to install: TensorFlow with CPU ...

  6. 【iOS系列】-xib封装使用

    [iOS系列]-xib封装使用 Xib文件可以用来描述某一块局部的UI界面 Xib文件的加载 修改xib文件的大小size(Freeform) 第一: NSArray *objs = [[NSBund ...

  7. Bash Shell 解析路径获取文件名称和文件夹名

    前言 还是今天再写一个自己主动化打包脚本.用到了从路径名中获取最后的文件名称.这里记录一下实现过程. 当然,最后我也会给出官方的做法.(ps:非常囧,实现完了才发现原来Bash Shell有现成的函数 ...

  8. 2016/05/06 Sublime Text 3 常用插件以及安装方法(转)

    http://www.cnsecer.com/460.html 安装Sublime Text 3插件的方法: 朋友们,小站活着不容易,全靠广告费养着了,如果本文对你有帮助.麻烦动下手点下页面的广告吧, ...

  9. visio 2010 修改 默认字体 字号大小 方法[整理]

    [转自]http://www.cnblogs.com/vegaliming/archive/2012/08/09/2630568.html 1.新建一个模具 2.将常用的图形放到这个模具中 3.对每个 ...

  10. 浏览器同部署了https的服务器交互的过程

    1 浏览器发起https请求 2 https服务器发送自己的公钥给浏览器 3 浏览器用https服务器发送过来的公钥加密一个用于双方通信的的对称密码 4 https服务器用自己的私钥解密,获取对称密码 ...