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. srand rand 随机函数

    srand函数是随机数发生器的初始化函数.原型:voidsrand(unsigned int seed); srand和rand()配合使用产生伪随机数序列.rand函数在产生随机数前,需要系统提供的 ...

  2. Process类的使用

    Process process= new Process(); process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellE ...

  3. 用SQL脚本 生成INSERT SQL语句

    配置表B 中的数据,可以从A表中查询到,在实际配置时,通过sql脚本生成B表的insert脚本,最多用到的是sql中连接符[||],以及双引号[''''] 例1:电销系统中地区出单机构关系表配置数据生 ...

  4. 快看Sample代码,速学Swift语言(2)-基础介绍 快看Sample代码,速学Swift语言(1)-语法速览

    快看Sample代码,速学Swift语言(2)-基础介绍 Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或 ...

  5. 全局最小割模版 n^3

    //点标从0-n-1, 開始时先init 复杂度n^3 //对于边(u,v,flow): //g[u][v]+=flow; //g[v][u]+=flow; typedef long long ll; ...

  6. [Sciter] 资源引用

    http://www.cnblogs.com/yinxufeng/p/fb343eecda564aa63bce0bdf15709ddf.html 方式一. 加载外部文件方式二. 加载内存方式三. 加载 ...

  7. web 界面设计---js设置txt值

    <head><meta http-equiv="Content-Type" content="text/html; charset=gb2312&quo ...

  8. HDU 2457/POJ 3691 DNA repair AC自动机+DP

    DNA repair Problem Description   Biologists finally invent techniques of repairing DNA that contains ...

  9. MYSQL之数据库初窥

    mysql数据库 1.数据库简单介绍    数据库概念:是依照数据结构来组织.存储和管理数据的仓库. 2.经常使用术语    数据库:是一些关联表的集合    数据表:表是数据的矩阵,在数据库中看起来 ...

  10. Error CREATEing SolrCore 'new_core': Unable to create core [new_core] Caused by: Can't find resource 'solrconfig.xml' in classpath or 'D:\solr\solr-7.2.1\server\solr\new_core'

    \solr-7.2.1\server\solr\configsets\_default  下的conf  复制到:   \solr-7.2.1\server\solr\new_core