并发编程-concurrent指南-线程池ExecutorService的实例
1、new Thread的弊端
执行一个异步任务你还只是如下new Thread吗?
new Thread(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
那你就out太多了,new Thread的弊端如下:
a. 每次new Thread新建对象性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread,Java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
1.CachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
public class ThreadRunner implements Runnable{
private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class CacheThreadPoolMain {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 1;i<21;i++){
pool.submit(new ThreadRunner(i,0));
}
pool.shutdown();
}
}
结果:
pool-1-thread-1:运行中,1
pool-1-thread-5:运行中,5
pool-1-thread-2:运行中,2
pool-1-thread-7:运行中,7
pool-1-thread-4:运行中,4
pool-1-thread-9:运行中,9
pool-1-thread-3:运行中,3
pool-1-thread-10:运行中,10
pool-1-thread-8:运行中,8
pool-1-thread-6:运行中,6
pool-1-thread-12:运行中,12
pool-1-thread-11:运行中,11
pool-1-thread-13:运行中,13
pool-1-thread-9:运行中,14
pool-1-thread-10:运行中,20
pool-1-thread-13:运行中,15
pool-1-thread-8:运行中,19
pool-1-thread-11:运行中,16
pool-1-thread-6:运行中,18
pool-1-thread-12:运行中,17
总结
- 池中线程时随着处理数据增加而增加
- 线程数并不是一直增加,如果有新任务需要执行时,首先查询池中是否有空闲线程并且还为到空闲截止时间,如果有,则使用空闲线程,如果没有,则创建新线程并放入池中。
- 用于执行一些生存期很短的异步型任务。不适用于IO等长延时操作,因为这可能会创建大量线程,导致系统崩溃。
- 使用SynchronousQueue作为阻塞队列,如果有新任务进入队列,必须队列中数据被其他线程处理,否则会等待。
2.FixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
import java.util.concurrent.TimeUnit; public class ThreadRunner implements Runnable{
private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class FixedThreadPoolMain {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);//有一个固定大小的线程池 for(int i = 1;i<21;i++){
pool.submit(new ThreadRunner(i,2));
} pool.shutdown();
}
}
总结:
- 池中线程数量固定,不会发生变化
- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。
- 适用一些很稳定很固定的正规并发线程,多用于服务器
3.ScheduledExcutorPool
创建一个定长线程池,支持定时及周期性任务执行。
ScheduledThreadPool中常用的ScheduleAtFixedRate和ScheduleWithFixedDelay
* ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
* 即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
* ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
* 即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
*
* ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
* ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit; public class ThreadRunner implements Runnable{
private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class ScheduledExcutorPoolMain {
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);//线程池 // 从现在开始5秒钟之后,每隔10秒钟执行一次ThreadRunner
pool.scheduleAtFixedRate(new ThreadRunner(2,3), 5,10, TimeUnit.SECONDS); // 从现在开始5秒钟之后,每隔10秒钟执行一次job2
pool.scheduleWithFixedDelay(new ThreadRunner(3,3), 5, 10, TimeUnit.SECONDS); /**
* ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
* 即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
* ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
* 即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
*
* ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
* ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
*/
}
}
总结:
- 线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。
- 只有当调度任务来的时候,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是出于轮询任务的状态
4.SingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照提交顺序被执行
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit; public class ThreadRunner implements Runnable{
private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class SingleThreadPool {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
for(int i=1;i<21;i++){
pool.submit(new ThreadRunner(i,5));
}
pool.shutdown();
}
}
结果:
pool-1-thread-1:当前时间:15:53:35.883,运行中,1
pool-1-thread-1:当前时间:15:53:40.884,运行中,2
pool-1-thread-1:当前时间:15:53:45.884,运行中,3
pool-1-thread-1:当前时间:15:53:50.884,运行中,4
pool-1-thread-1:当前时间:15:53:55.884,运行中,5
pool-1-thread-1:当前时间:15:54:00.885,运行中,6
pool-1-thread-1:当前时间:15:54:05.885,运行中,7
pool-1-thread-1:当前时间:15:54:10.886,运行中,8
pool-1-thread-1:当前时间:15:54:15.886,运行中,9
pool-1-thread-1:当前时间:15:54:20.887,运行中,10
pool-1-thread-1:当前时间:15:54:25.887,运行中,11
pool-1-thread-1:当前时间:15:54:30.887,运行中,12
pool-1-thread-1:当前时间:15:54:35.888,运行中,13
pool-1-thread-1:当前时间:15:54:40.888,运行中,14
pool-1-thread-1:当前时间:15:54:45.888,运行中,15
pool-1-thread-1:当前时间:15:54:50.888,运行中,16
pool-1-thread-1:当前时间:15:54:55.889,运行中,17
pool-1-thread-1:当前时间:15:55:00.889,运行中,18
pool-1-thread-1:当前时间:15:55:05.889,运行中,19
pool-1-thread-1:当前时间:15:55:10.890,运行中,20
总结:
- 线程中只有一个线程在执行
- 适用于有明确执行顺序但是不影响主线程的任务,压入池中的任务会按照队列顺序执行。
- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。
源码地址:https://github.com/qjm201000/concurrent_executorService.git
并发编程-concurrent指南-线程池ExecutorService的实例的更多相关文章
- 并发编程-concurrent指南-线程池ExecutorService的使用
有几种不同的方式来将任务委托给 ExecutorService 去执行: execute(Runnable) submit(Runnable) submit(Callable) invokeAny(… ...
- Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析
目录 引出线程池 Executor框架 ThreadPoolExecutor详解 构造函数 重要的变量 线程池执行流程 任务队列workQueue 任务拒绝策略 线程池的关闭 ThreadPoolEx ...
- Java并发编程:Java线程池
转载自:http://www.cnblogs.com/dolphin0520/p/3932921.html 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题 ...
- 【Java并发编程六】线程池
一.概述 在执行并发任务时,我们可以把任务传递给一个线程池,来替代为每个并发执行的任务都启动一个新的线程,只要池里有空闲的线程,任务就会分配一个线程执行.在线程池的内部,任务被插入一个阻塞队列(Blo ...
- 并发编程-concurrent指南-原子操作类-AtomicInteger
在java并发编程中,会出现++,--等操作,但是这些不是原子性操作,这在线程安全上面就会出现相应的问题.因此java提供了相应类的原子性操作类. 1.AtomicInteger
- day33_8_15 并发编程4,线程池与协程,io模型
一.线程池 线程池是一个处理线程任务的集合,他是可以接受一定量的线程任务,并创建线程,处理该任务,处理结束后不会立刻关闭池子,会继续等待提交的任务,也就是他们的进程/线程号不会改变. 当线程池中的任务 ...
- 并发编程 --进、线程池、协程、IO模型
内容目录: 1.socket服务端实现并发 2.进程池,线程池 3.协程 4.IO模型 1.socket服务端实现并发 # 客户端: import socket client = socket.soc ...
- Java并发编程 (九) 线程调度-线程池
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 声明:实际上,在开发中并不会普遍的使用Thread,因为它具有一些弊端,对并发性能的影响比较大,如下: ...
- 并发编程-concurrent指南-Lock-可重入锁(ReentrantLock)
可重入和不可重入的概念是这样的:当一个线程获得了当前实例的锁,并进入方法A,这个线程在没有释放这把锁的时候,能否再次进入方法A呢? 可重入锁:可以再次进入方法A,就是说在释放锁前此线程可以再次进入方法 ...
随机推荐
- VMware Workstation克隆linux虚拟机操作
1.删除MAC地址,修改IP [root@xuegod63 network-scripts]# vim ifcfg-eth0 [root@xuegod63 network-scripts]# cat ...
- WPF依赖属性对内存的使用方式
WPF允许对象在创建时候并不包含存储数据的空间,只保留在用到时获取数据默认值,借用其他对象数据或者实时分配空间的能力
- windows服务的编写,手动安装与卸载
windows服务的编写 1.要添加的引用 using System.ServiceProcess; using System.ServiceModel ; using WcfServiceLibra ...
- Hermite曲线插值
原文 Hermite Curve Interpolation Hermite Curve Interpolation Hamburg (Germany), the 30th March 1998. W ...
- Android Camera2拍照(一)——使用SurfaceView
原文:Android Camera2拍照(一)--使用SurfaceView Camera2 API简介 Android 从5.0(21)开始,引入了新的Camera API Camera2,原来的a ...
- 超详细SQL SERVER 2016跨网段和局域网发布订阅配置图解和常见问题
原文:超详细SQL SERVER 2016跨网段和局域网发布订阅配置图解和常见问题 转载标明出处:http://blog.csdn.net/u012861467 前方高能,要有点耐心,图片较多,注意在 ...
- RxJava入门优秀博客推荐
RxJava用了快半年了,现在越来越离不开这个库,从使用到逐渐接触它的背后实现,突然想写点什么关于RxJava的内容.在酝酿如何组织内容的时候,就去看看自己关于RxJava的收藏,发现满满的干货! 1 ...
- Bamboo 0.2.11 发布,HAProxy 自动配置
Bamboo 0.2.11 发布,此版本更新内容如下: 新特性 提供更多的模板字符串函数:strings.Split, strings.Join,strings.Replace, strings.T ...
- 自己总结OpenSSL的变化
经过查看openssl源码自带的Makefile,发现: 1) 从0.9.7开始 https://www.openssl.org/source/old/0.9.x/openssl-0.9.7k.tar ...
- MySQL5.7.19版本压缩包安装方式的一些坑
ySQL社区版下载地址:https://dev.mysql.com/downloads/mysql/,在这里也可以选择之前的版本下载. MySQL进入5.7.7版本以后,压缩包安装需要注意一些地方: ...