关于线程池的创建,可以直接使用Executor所属的方法来创建,代码如下。
//可重用固定个数线程池,以共享的无界队列方式来运行这些线程
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int n);
//可缓存线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//单线程化线程池,只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
//定长线程池,支持定时以及周期性任务执行
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int n);
需要注意的是,虽然这四种线程池都属于java.util.concurrent包下,但是ScheduledThreadPool和其他三种线程池不在同一个包下,代码如下
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
其中,FixedThreadPool以及SingleThreadExecutor可能会造成大量的请求堆积,导致OOM
CachedThreadPool和ScheduledThreadPool可能会创建大量的线程,导致OOM
所以推荐使用的还是ThreadPoolExecutor
一般来讲我们使用的都是默认的ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue)
在Java8中源码如下:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default thread factory and rejected execution handler.
* It may be more convenient to use one of the {@link Executors} factory
* methods instead of this general purpose constructor.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
从注释说明中可以看到,使用ThreadPoolExecutor时,会使用默认的thread factory和拒绝策略
然后就是建议直接使用Executors的方法,所以可以忽略这句话
具体的参数说明为:
corePoolSize:线程池中需要保持的线程数量,即使他们是闲置的状态,除非设置allowCoreThreadTimeOut
maximumPoolSize:线程池中允许的最大数量
keepAliveTime:corePoolSize中的线程之外的等待线程,最大等待时间
unit:keepAliveTime的时间单位
workQueue:执行前的等待队列,可以用Runnable的execute方法运行
需要注意的是:
(1)corePoolSize、keepAliveTime不能小于0
maximumPoolSize不能小于等于0
maximumPoolSize不能小于corePoolSize
否则会出现IllegalArgumentException
(2)workQueue不能为空
否则会出现NullPointerException
其中ThreadFactory和RejectedExecutionHandler也可以两个都自定义,也可以只自定义ThreadFactory,使用默认的RejectedExecutionHandler,并且在完全自定以的源码中会更直观的看到参数的范围等。
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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
线程池的拒绝策略:
AbortPolicy,终止策略,报出异常并终止运行(默认的拒绝策略)
CallerRunsPolicy,把任务交给当前线程来运行
DiscardPolicy,忽略此次任务(最新的任务)
DiscardOlderPolicy,忽略最早的任务(最先加入队列的任务)