Android 线程池系列教程(3) 创建线程池
1.This lesson teaches you to
2.You should also read
3. Try it out
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
Runnabletypes, 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
synchronizedblock: -
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
Handlerin the constructor and attach it to your app's UI thread. - A
Handlerallows your app to safely call the methods of UI objects such asViewobjects. 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
ThreadPoolExecutortakesRunnableobjects. To start code on a thread, a thread pool manager takes aRunnableobject 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 theBlockingQueueinterface. 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 theLinkedBlockingQueueclass: -
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) 创建线程池的更多相关文章
- Android 线程池系列教程(4) 启动线程池中的线程和中止池中线程
Running Code on a Thread Pool Thread 上一课 下一课 1.This lesson teaches you to Run a Runnable on a Thre ...
- 线程池ThreadPoolExecutor分析: 线程池是什么时候创建线程的,队列中的任务是什么时候取出来的?
带着几个问题进入源码分析: 1. 线程池是什么时候创建线程的? 2. 任务runnable task是先放到core到maxThread之间的线程,还是先放到队列? 3. 队列中的任务是什么时候取出来 ...
- Java并发——ThreadPoolExecutor线程池解析及Executor创建线程常见四种方式
前言: 在刚学Java并发的时候基本上第一个demo都会写new Thread来创建线程.但是随着学的深入之后发现基本上都是使用线程池来直接获取线程.那么为什么会有这样的情况发生呢? new Thre ...
- Mysql线程池系列一:什么是线程池和连接池( thread_pool 和 connection_pool)
thread_pool 和 connection_pool 当客户端请求的数据量比较大的时候,使用线程池可以节约大量的系统资源,使得更多的CPU时间和内存可以高效地利用起来.而数据库连接池的使用 ...
- Spring Boot2 系列教程(二)创建 Spring Boot 项目的三种方式
我最早是 2016 年底开始写 Spring Boot 相关的博客,当时使用的版本还是 1.4.x ,文章发表在 CSDN 上,阅读量最大的一篇有 43W+,如下图: 2017 年由于种种原因,就没有 ...
- Android 线程池系列教程(5)与UI线程通信要用Handler
Communicating with the UI Thread 上一课 下一课 1.This lesson teaches you to Define a Handler on the UI Thr ...
- Android 线程池系列教程(2)Thread,Runnable是基类及如何写Run方法
Specifying the Code to Run on a Thread 上一课 下一课 1.This lesson teaches you to Define a Class that Im ...
- Android 线程池系列教程(1)目录
Sending Operations to Multiple Threads 1.Dependencies and prerequisites Android 3.0 (API Level 11) o ...
- [C# 线程处理系列]专题四:线程同步
目录: 一.线程同步概述 二.线程同步的使用 三 .总结 一.线程同步概述 前面的文章都是讲创建多线程来实现让我们能够更好的响应应用程序,然而当我们创建了多个线程时,就存在多个线程同时访问一个共享的资 ...
随机推荐
- [NPM] npm check to update the dependencies
To update the dependencies in the project, we can run: npx npm-check -u
- 全栈JavaScript之路(十六)HTML5 HTMLDocument 类型的变化
HTML5 扩展了 HTMLDocument, 添加了新的功能. 1.document.readState = 'loading' || 'complete' //支持readyState 属性的浏 ...
- js常用的正则表达操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- CSS的两个class选择器紧挨在一起
有一段HTML代码: <a class="glyphicons white no-js cogwheel" href="#" target="_ ...
- 2016/3/21 面向对象: ①定义类 ②实例化对象 ③$this关键字 ④构造函数 ⑤析构函数 ⑥封装 ⑦继承
一:定义类 二:实例化对象 //定义类 class Ren { var $name; var $sex; var $age; function Say() { echo "{$this- ...
- UVA11383 Golden Tiger Claw —— KM算法
题目链接:https://vjudge.net/problem/UVA-11383 题解: 根据KM()算法,标杆满足:l(x) + l(y) >= w(x, y) . 当求完最大权匹配之后,所 ...
- Basic Queries (LINQ to XML)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-queries-linq-to ...
- oracle 建表 主键自增序列/////
oracle 建表 主键自增序列 (2011-10-12 11:59:22) 转载▼ 标签: 杂谈 分类: oracle SQL> create table sms_activity( 2 ...
- 【idea】idea快捷键
Alt+回车 导入包,自动修正 alt+shift+↑ 向上sout输出 psvm主函数 fori for Ctrl+N 查找类Ctrl+Shift+N 查找文件Ctrl+Alt+L 格式化代 ...
- javascript base64 编码,兼容ie6789
用Javascript进行base64编码,在高版本的IE浏览器(IE9以上版本),和firefox,chrome浏览器里是非常方便的.这些浏览器的window对象中内置了base64的编码和解码方法 ...