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. Deepin-安装QQ音乐(Windows程序)

    打开命令行,输入: sudo apt-get install wine 安装完成后,下载QQ音乐的安装包 然后安装 示例:wine xx.exe 实例:wine QQMusic.exe 安装完成,启动 ...

  2. Binder IPC的权限控制

    PS:个人理解:当进程1通过Binder调用组件2时,会将进程1的pid及uid赋给组件2,并检测进程1的pid及uid是否有权限调用组件2.而后组件2需要调用组件3,此时组件2保存的pid及uid为 ...

  3. 无限级分类Asp.net Mvc实现

    无限级分类Asp.net Mvc实现   无限级分类涉及到异步加载子类.加载当前类和匹配问题,现在做一个通用的实现.   (一) 效果如下:   (二)设计.实现及使用 (1)数据库 (a)表设计db ...

  4. android 怎样将主菜单图标改成按安装时间排序

    1. 在 LauncherModel.java 中增加例如以下代码, 假设是KK Launcher3 ApplicationInfo要替换为AppInfo public static final Co ...

  5. 【ios系列】-Quartz 2D常用方法介绍

    Quartz 2D基本介绍 Quartz 2D是一个二维绘图引擎 能够,绘制图形 : 线条\三角形\矩形\圆\弧等,绘制文字,绘制\生成图片(图像),读取\生成PDF,截图\裁剪图片,自定义UI控件( ...

  6. Intellig Idea2017新建Web项目(tu'wen)

    1.新建新工程项目 2.选择Java 和JDK版本 3.下一步Next(默认不勾选) 4.设置Project Name ,点击More Setting图标可以折叠.展开  然后Finish 我们可以看 ...

  7. linux下信息分屏显示

    在字符界面下,经常遇到ls之后信息太长,只能看到最后一页的信息,这时就需要分屏显示了. 常用: ls | less 这样就可以分屏显示了,并可以用PgUp和PgDn来上下翻页. 也可以用: ls | ...

  8. memmove 和 memcopy

    1.memmove 函数原型:void *memmove(void *dest, const void *source, size_t count) 返回值说明:返回指向dest的void *指针 参 ...

  9. apache httpd 2.4 httpd

    This is a wiki containing user-contributed recipes, tips, and tricks for the Apache HTTP Server (aka ...

  10. 递归读取制定目录下所有文件夹和文件的实现(java)

    public static String getAllDirectorisAndFiles(String path){ Map<String, Object> responseMap = ...