Android 四种常见的线程池
引入线程池的好处
1)提升性能。创建和消耗对象费时费CPU资源
2)防止内存过度消耗。控制活动线程的数量,防止并发线程过多。
我们来看一下线程池的简单的构造
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {...}
使用上面的方式创建线程池的话,我们需要配置一堆东西,非常麻烦,所以我们不建议这么使用。而是推荐使用Executors的工厂方法来创建线程池,Executors类是官方提供的一个工厂类,它里面封装好了众多功能不一样的线程池。下面就介绍几个常用的线程池。
public ThreadPoolExecutor( //核心线程数,除非allowCoreThreadTimeOut被设置为true,否则它闲着也不会死 int corePoolSize, //最大线程数,活动线程数量超过它,后续任务就会排队 int maximumPoolSize, //超时时长,作用于非核心线程(allowCoreThreadTimeOut被设置为true时也会同时作用于核心线程),闲置超时便被回收 long keepAliveTime, //枚举类型,设置keepAliveTime的单位,有TimeUnit.MILLISECONDS(ms)、TimeUnit. SECONDS(s)等 TimeUnit unit, //缓冲任务队列,线程池的execute方法会将Runnable对象存储起来 BlockingQueue<Runnable> workQueue, //线程工厂接口,只有一个new Thread(Runnable r)方法,可为线程池创建新线程 ThreadFactory threadFactory)
1、FixedThreadPool() :
栗子:假如有一个新任务提交时,线程池中如果有空闲的线程则立即使用空闲线程来处理任务,如果没有,则会把这个新任务存在一个任务队列中,一旦有线程空闲了,则按FIFO方式处理任务队列中的任务。
public static ExecutorService newFixThreadPool(int nThreads){
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
//使用
Executors.newFixThreadPool(5).execute(r);
2、CachedThreadPool() :
栗子:假如该线程池中的所有线程都正在工作,而此时有新任务提交,那么将会创建新的线程去处理该任务,而此时假如之前有一些线程完成了任务,现在又有新任务提交,那么将不会创建新线程去处理,而是复用空闲的线程去处理新任务。那么此时有人有疑问了,那这样来说该线程池的线程岂不是会越集越多?其实并不会,因为线程池中的线程都有一个“保持活动时间”的参数,通过配置它,如果线程池中的空闲线程的空闲时间超过该“保存活动时间”则立刻停止该线程,而该线程池默认的“保持活动时间”为60s。
public static ExecutorService newCachedThreadPool(int nThreads){
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue<Runnable>());
}
//使用
Executors.newCachedThreadPool().execute(r);
3、SingleThreadExecutor() :
该方法返回一个只有一个线程的线程池,即每次只能执行一个线程任务,多余的任务会保存到一个任务队列中,等待这一个线程空闲,当这个线程空闲了再按FIFO方式顺序执行任务队列中的任务。
public static ExecutorService newSingleThreadPool (int nThreads){
return new FinalizableDelegatedExecutorService ( new ThreadPoolExecutor (1, 1, 0, TimeUnit. MILLISECONDS, new LinkedBlockingQueue<Runnable>()) );
}
//使用
Executors.newSingleThreadPool ().execute(r);

4、ScheduledThreadPool() :
该方法返回一个可以控制线程池内线程定时或周期性执行某任务的线程池。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize){
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedQueue ());
}
//使用,延迟1秒执行,每隔2秒执行一次Runnable r
Executors. newScheduledThreadPool (5).scheduleAtFixedRate(r, 1000, 2000, TimeUnit.MILLISECONDS);
自定义线程池
1)创建一个基于PriorityBlockingQueue的线程池
ExecutorService priorityThreadPool = new ThreadPoolExecutor(3,3,0L,TimeUnit.SECONDS,new PriorityBlockingQueue());
2)创建一个实现Runnable接口的类,并向外提供我们实现自定义功能,并实现Comparable接口
public abstract class PriorityRunnable implements Runnable, Comparable {
private int priority;
public PriorityRunnable(int priority) {
if (priority 0)
throw new IllegalArgumentException();
this.priority = priority;
}
@Override
public int compareTo(PriorityRunnable another) {
int my = this.getPriority();
int other = another.getPriority();
return my 1 : my > other ? -1 : 0;
}
@Override
public void run() {
doSth();
}
public abstract void doSth();
public int getPriority() {
return priority;
}
}
3)使用PriorityRunnable提交任务
ExecutorService priorityThreadPool = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.SECONDS, new PriorityBlockingQueue());
for (int i = 1; i 10; i++) {
final int priority = i;
priorityThreadPool.execute(new PriorityRunnable(priority) {
@Override
public void doSth() {
String threadName = Thread.currentThread().getName();
Log.v("zxy", "线程:" + threadName + ",正在执行优先级为:" + priority + "的任务");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
Android 四种常见的线程池的更多相关文章
- Java 四种内置线程池
引言 我们之前使用线程的时候都是使用 new Thread 来进行线程的创建,但是这样会有一些问题 每次 new Thread 新建对象性能差 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可 ...
- java开发中几种常见的线程池
线程池 java.util.concurrent:Class Executors 常用线程池 几种常用的的生成线程池的方法: newCachedThreadPool newFixedThreadPoo ...
- Android 多线程: 完全解析线程池ThreadPool原理&使用
目录 1. 简介 2. 工作原理 2.1 核心参数 线程池中有6个核心参数,具体如下 上述6个参数的配置 决定了 线程池的功能,具体设置时机 = 创建 线程池类对象时 传入 ThreadPoolExe ...
- 四种常见的App弹窗设计,你有仔细注意观察吗?
弹窗又称为对话框,是App与用户进行交互的常见方式之一.弹窗分为模态弹窗和非模态弹窗两种,两者的区别在于需不需要用户对其进行回应.模态弹窗会打断用户的正常操作,要求用户必须对其进行回应,否则不能继续其 ...
- (转)四种常见的 POST 提交数据方式
四种常见的 POST 提交数据方式(转自:https://imququ.com/post/four-ways-to-post-data-in-http.html) HTTP/1.1 协议规定的 HTT ...
- 四种常见的提示弹出框(success,warning,error,loading)原生JavaScript和jQuery分别实现
原文:四种常见的提示弹出框(success,warning,error,loading)原生JavaScript和jQuery分别实现 虽然说现在官方的自带插件已经有很多了,但是有时候往往不能满足我们 ...
- 一文读懂四种常见的XML解析技术
之前的文章我们讲解了<XML系列教程之Schema技术_上海尚学堂java培训技术干货><XML的概念.特点与作用.XML申明_上海Java培训技术干货>,大家可以点击回顾一下 ...
- 四种常见的 POST 提交数据方式(application/x-www-form-urlencoded,multipart/form-data,application/json,text/xml)
四种常见的 POST 提交数据方式(application/x-www-form-urlencoded,multipart/form-data,application/json,text/xml) 转 ...
- application/json 四种常见的 POST 提交数据方式
四种常见的 POST 提交数据方式 HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS.GET.HEAD.POST.PUT.DELETE.TRACE.CONNECT 这几种.其中 ...
随机推荐
- HDU 5726 GCD 区间GCD=k的个数
GCD Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submis ...
- 2015 多校联赛 ——HDU5360(贪心+优先队列)
Sample Input 4 8 4 1 3 2 2 1 0 3 5 3 6 4 2 1 7 6 8 3 3 2 0 5 0 3 6 4 5 2 7 7 6 7 6 8 2 2 3 3 3 0 0 2 ...
- hdu 5643 BestCoder Round #75
King's Game Accepts: 249 Submissions: 671 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 6 ...
- 关于mysql初始化以及安全策略无法修改的问题
通过mysql官方的yum源来安装的mysql-community-server ,这里版本是MySQL 8.0. wget rpm -ivh mysql80-community-release- ...
- 如何使用 TeamViewer 配置QuickConnect按钮?
QuickConnect作为TeamViewer中一个比较重要的部分,得到了很多用户的认可.那么在实际运用中,怎么才能设置网页或单个程序的QuickConnect呢?所以小编以此问题为例,教大家如何配 ...
- VGG网路结构
VGG网络的基本结构 如图所示,从A到E网络的深度是逐渐增加的,在A中有11个权重层(8个卷积层,3个全连接层),在E中有19个权重层(16个卷积层,3个全连接层),卷积层的宽度是十分小的,开始时在第 ...
- fastDFS 安装 配置 使用
fastDFS 安装 配置 使用 关于安装 本文采用的是源码的安装方式,其他安装方式请自行百度 简单介绍 1.背景 FastDFS是一款开源的.分布式文件系统(Distributed File Sys ...
- 31. Next Permutation(中等,搞清楚啥是 next permutation)
Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...
- TP中的AJAX返回ajaxReturn()
系统支持任何的AJAX类库,Action类提供了ajaxReturn方法用于AJAX调用后返回数据给客户端.并且支持JSON.XML和EVAL三种方式给客户端接受数据,通过配置DEFAULT_AJAX ...
- asp.net使用session完成: 从哪个页面进入登录页面,登录成功还回到那个页面
1.在Login.aspx页面Load中加入 if (!IsPostBack && Request.UrlReferrer != null) { Session[ " ...