创建线程池的正确姿势

小伙伴都知道通过Executors静态类可以直接创建4种类型的线程池,

但读过阿里巴巴开发手册的童鞋一定见过这句话:

强烈不建议直接使用Executors静态类来创建线程池!!!

这是为啥呢? 原因如下:

1:FixedThreadPool 和 SingleThreadPool:
允许的请求队列(底层实现是LinkedBlockingQueue)长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM

2:CachedThreadPool 和 ScheduledThreadPool
允许的创建最大线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。

说白了,避免使用Executors创建线程池,主要是避免使用其中的默认实现(可能会导致OOM),

那么我们可以自己直接调用ThreadPoolExecutor的构造函数来自己创建线程池。在创建的同时,给BlockQueue指定容量就可以了。

先看看它的(参数最全)构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
  ...
}

如下创建即可(ThreadFactory 和RejectedExecutionHandler 两个参数可以是非必传参数):
ExecutorService executor = new ThreadPoolExecutor(10, 10, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue(10));

一张图解释下线程池的稽核核心参数:

 两张图解释下线程池的运行流程:

 

原文地址:https://www.cnblogs.com/Baker-Street/p/15022212.html