java 四种executor_Java ExecutorService四种线程池及自定义ThreadPoolExecutor机制

一、Java 线程池

Java通过Executors提供四种线程池,分别为:

1、newCachedThreadPool:创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。(线程最大并发数不可控制);线程池为无限大,当执行第二个任务时若第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

2、newFixedThreadPool:创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

3、newScheduledThreadPool:创建一个定长线程池,支持定时及周期性任务执行、延迟执行。

4、newSingleThreadExecutor:创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

线程池比较单线程的优势在于:

a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。

b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。

c. 提供定时执行、定期执行、单线程、并发数控制等功能。

二、ThreadPoolExecutor机制

1、newCachedThreadPool

public staticExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue());

}

2、newFixedThreadPool

public static ExecutorService newFixedThreadPool(intnThreads) {return newThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue());

}

3、newScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(intcorePoolSize) {return newScheduledThreadPoolExecutor(corePoolSize);

}public ScheduledThreadPoolExecutor(intcorePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,newDelayedWorkQueue());

}public ThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,

TimeUnit unit,

BlockingQueueworkQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,

Executors.defaultThreadFactory(), defaultHandler);

}

4、newSingleThreadExecutor

public staticExecutorService newSingleThreadExecutor() {return newFinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue()));

}

这几种线程池最终都是返回了ThreadPoolExecutor对象。

ThreadPoolExecutor的构造方法:

public ThreadPoolExecutor(int corePoolSize,//核心线程池大小

int maximumPoolSize,//最大线程池大小

long keepAliveTime,//线程池中超过corePoolSize数目的空闲线程最大存活时间;可以allowCoreThreadTimeOut(true)成为核心线程的有效时间

TimeUnit unit,//keepAliveTime的时间单位

BlockingQueue workQueue,//阻塞任务队列

ThreadFactory threadFactory,//线程工厂

RejectedExecutionHandler handler) {//当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理

if (corePoolSize < 0 ||maximumPoolSize<= 0 ||maximumPoolSize< corePoolSize ||keepAliveTime< 0)throw newIllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw newNullPointerException();this.corePoolSize =corePoolSize;this.maximumPoolSize =maximumPoolSize;this.workQueue =workQueue;this.keepAliveTime =unit.toNanos(keepAliveTime);this.threadFactory =threadFactory;this.handler =handler;

}

重点讲解:

其中比较容易让人误解的是:corePoolSize,maximumPoolSize,workQueue之间关系:

1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。

2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行

3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务

4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理

5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程

6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭

学会使用ThreadPoolExecutor的参数后,我们就可以不用局限于最上面那四种线程池,可以按照需要来构建自己的线程池;还有一点,通过ThreadFactory可以实现对线程的命名;

自定义线程工厂管理线程池:使用spring初始化实例类,使用同步锁将线程池封装到线程集合中;

/**

* @program: airplane-common

* @Date: 2019/1/7 15:54

* @Author: zhenliang.song

* @Description: 使用ThreadPoolExecutor自定义线程池

*/

public class ExecutorPoolFactoryWrap {

/**

* 线程池集合:key-自定义的枚举类型,value-线程池的接口类型,初始化集合长度为枚举类的values长度

*/

private ConcurrentHashMap PoolFactoryMap = new ConcurrentHashMap(ThreadPoolEnum.values().length);

/**

* 从集合中获取线程池对象:根据枚举类型映射map集合中的自定义线程对象

* @param poolEnum 枚举类

* @return

*/

public ExecutorService get(ThreadPoolEnum poolEnum) {

ExecutorService executorService = PoolFactoryMap.get(poolEnum);

if (executorService != null) {

return executorService;

}

synchronized (ExecutorPoolFactoryWrap.class) {

if (PoolFactoryMap.get(poolEnum) == null) {

int poolSize = poolEnum.getPoolSize() > 0 ? poolEnum.getPoolSize() : 1;

int capacity = poolEnum.getCapacity() > 0 ? poolEnum.getCapacity() : 256;

RejectedExecutionHandler rejectedHandler = poolEnum.getRejectedHandler() != null ? poolEnum.getRejectedHandler() : getRejectedExecutionHandler();

ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(poolEnum.getPoolName() + "-%d").build();

PoolFactoryMap.put(poolEnum, new ThreadPoolExecutor(poolSize, poolSize,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue(capacity),

threadFactory,

rejectedHandler

));

}

}

return PoolFactoryMap.get(poolEnum);

}

/**

* 当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理,

* 当没有更多的线程或队列插槽时,自定义如何处理超出能力范围之外的任务

* @return

*/

private RejectedExecutionHandler getRejectedExecutionHandler() {

return new RejectedExecutionHandler() {

public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

if (!executor.isShutdown()) {

r.run();

}

}

};

}

/**

* 销毁线程池:销毁集合中的线程池

*/

public void destroy() {

if (MapUtils.isEmpty(PoolFactoryMap)) {

return;

}

for (Map.Entry entry : PoolFactoryMap.entrySet()) {

ExecutorService executorService = entry.getValue();

try {

if (executorService != null && !executorService.isShutdown()) {

executorService.shutdown();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

原文:https://www.cnblogs.com/aoshicangqiong/p/10233977.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值