文章目录
参数
下面是 ThreadPoolExecutor 其中一个构造方法,可以看到 ThreadPoolExecutor 一共有7个参数:
- corePoolSize:核心线程数,默认创建出来后不会被回收,可以通过调用allowCoreThreadTimeOut(true)方法允许回收
- maximumPoolSize:最大线程数
- keepAliveTime:当线程数大于核心线程数时,多余的线程等待任务的时间,超过时间没有分配到任务被回收
- unit:传入的 keepAliveTime 的单位
- workQueue:工作队列,当核心线程数满了后,任务将加入此队列,队列满后判断是否达到最大线程数,如果没有,创建新的线程执行任务,否则执行拒绝策略
- threadFactory:线程工厂
- handler:拒绝策略,默认拒绝策略为 AbortPolicy(抛出RejectedExecutionException异常)
过程:先创建核心线程执行任务,核心线程满了后放到工作队列,队列满后判断是否达到最大线程数,如果没有,创建新的线程执行任务,否则执行拒绝策略
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
拒绝策略
一共有四种拒绝策略:
- AbortPolicy,抛出 RejectedExecutionException 异常(默认的拒绝策略)
- DiscardPolicy,抛弃任务,下面源码中可以看到该策略的 rejectedExecution 方法为空方法
- DiscardOldestPolicy,丢弃最早的未处理的任务
- CallerRunsPolicy,由调用 execute 方法的线程直接执行该任务
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
/**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method,
* unless the executor has been shut down, in which case the task
* is discarded.
*/
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
线程池工具类 Executors 提供的部分线程池
- FixedThreadPool
- SingleThreadExecutor
- CachedThreadPool
- ScheduledThreadPool
FixedThreadPool
FixedThreadPool 将核心线程数和最大线程数都设为传入的 nThreads,工作队列使用 LinkedBlockingQueue,从LinkedBlockingQueue 构造方法可以看到,该队列最大长度为 Integer.MAX_VALUE,容易造成内存溢出
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
SingleThreadExecutor
SingleThreadExecutor 将核心线程数和最大线程数都设为 1,工作队列也使用 LinkedBlockingQueue,容易造成内存溢出(该队列最大长度为 Integer.MAX_VALUE)
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
CachedThreadPool
CachedThreadPool 将核心线程数设为 0,最大线程数都设为 Integer.MAX_VALUE
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
ScheduledThreadPool
将最大线程数设为 Integer.MAX_VALUE
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
Executors 提供的线程池要么最大线程数要么工作队列的长度为 Integer.MAX_VALUE,容易造成内存溢出,所以实际上基本都使用自定义的线程池。
自定义线程池根据业务类型设置线程数:
IO密集型设为 2*cpu核数
cpu密集型设为 cpu核数+1
混合业务可以拆分为IO型+cpu型
线程数这样设置只是大概参数,想要更精准需要通过测试获得一个比较合适的数量