Leave01

导航

线程池原理及使用

一、Executor 线程池体系介绍

1. Executor 框架体系介绍

  • Executor: java线程池框架的最上层父接口,在Executor中只有executor()方法,该方法表示提交Runnable类型线程池并执行。

  • ExecutorService: Executor的子接口,该接口中submit()方法可接收Runnable参数或Callable参数,在使用结束后使用shutdown()方法关闭线程池,不再接收新的任务。

  • AbstractExecutorService: ExecutorService的默认实现类。

  • ScheduledExecutorService: ExecutorService的子接口,可供定时任务调度的接口。

  • ScheduledThreadPoolExecutor: 提供了另一种线程池,延迟执行和周期性执行的线程池。

  • ThreadPoolExecutor: Java线程池最核心的一个类,该类继承自AbstractExecutorService主要功能是创建线程池,给任务分配线程资源,执行任务。

2. ThreadPoolExecutor 源码解析

ThreadPoolExecutor有多个重载的构造方法,我们基于最完整的构造方法来分析每个参数的作用。

public ThreadPoolExecutor(int corePoolSize,	//核心线程池数量
int maximumPoolSize,	//最大线程池数量
long keepAliveTime,	//线程数大于核心线程池数,空闲线程的最大存活时间
TimeUnit unit,	//参数的时间单位
BlockingQueue<Runnable> workQueue,	//线程等待队列
ThreadFactory threadFactory,	//用于设置创建线程的工厂
RejectedExecutionHandler handler) {	//设置拒绝策略
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}

二、Executors 线程池工具类

1. newFixedThreadPool: 固定大小线程池

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
  • corePoolSize与maximumPoolSize相等,即其线程全为核心线程,是一个固定大小的线程池,是其优势;
  • keepAliveTime = 0 该参数默认对核心线程无效,而FixedThreadPool全部为核心线程;
  • workQueue 为LinkedBlockingQueue(无界阻塞队列),队列最大值为Integer.MAX_VALUE。如果任务提交速度持续大余任务处理速度,会造成队列大量阻塞。因为队列很大,很有可能在拒绝策略前,内存溢出。是其劣势;
  • FixedThreadPool的任务执行是无序的;

2. newSingleThreadExecutor: 单线程化线程池

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
  • 控制线程池中corePoolSize与maximumPoolSize都为1
  • FinalizableDelegatedExecutorService继承DelegatedExecutorService,DelegatedExecutorService最终继承AbstractExecutorService,该类是线程池的一个代理模式的实现,相比于ThreadPoolExecutor阉割一部分功能,形成线程池单例化。

3. newCachedThreadPool: 可缓存线程池

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
  • corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即线程数量几乎无限制
  • keepAliveTime = 60s,60s后空闲线程自动结束
  • SynchronousQueue 为同步队列,入队出队必须同时传递,因为CachedThreadPool线程创建无限制,不会有队列等待

4. newScheduledThreadPool: 周期性线程池

public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
  • newScheduledThreadPool为定长线程池,限定核心线程数
  • ScheduledThreadPoolExecutor方法中对线程池参数做了进一步的封装,设置maximumPoolSize = Integer.MAX_VALUE,keepAliveTime = 0
  • 调用scheduleAtFixedRate()方法可进行周期性任务设置

5. newWorkStealingPool: 工作窃取线程池(jdk1.8)

public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
  • ForkJoinPool继承AbstractExecutorService,ForkJoinPool可以充分利用多核cpu的优势,将一个任务拆分成多个“小任务”并行计算,提高任务的执行时间

posted on 2019-10-29 17:44  Leave01  阅读(535)  评论(0)    收藏  举报