线程池参数
Java线程池七个参数详解
首先来看一下ThreadPoolExecutor的构造方法,其中需要传入的7大参数分别是corePoolSize、maximumPoolSize、keepAliveTime、unit、workQueue、threadFactory、handler
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;
}
- @param corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is setallowCoreThreadTimeOut
corePoolSize:线程池核心线程大小,线程池会维护一个最低连接数量,即使处于空闲状态,也不会销毁它,除非设置了
- @param maximumPoolSize the maximum number of threads to allow in the pool
maximumPoolSize :线程的最大连接数;一个任务被提交到线程中,会先缓存到队列中,如果工作队列已满,就新建一个线程来执行队列中的任务,这时工作队列就会腾出空间给先来的任务。线程的创建不会无休止的,这里maximumPoolSize 就是限制创建的最大数量
- @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.
keepAliveTime :空闲线程存活时间;当线程的数量大于核心(corePoolSize)时,这是多余的空闲线程在终止之前等待新任务的最大时间。
- @param unit the time unit for the {@code keepAliveTime} argument
code keepAliveTime参数的时间单位
- @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.
workQueue :新任务被提交后,会先进入到此工作队列中,任务调度时再从队列中取出任务
工作队列jdk实现了4个,分别是ArrayBlockingQueue、LinkedBlockingQuene、SynchronousQuene、PriorityBlockingQueue
- @param threadFactory the factory to use when the executor creates a new thread
创建一个新线程时使用的工厂,可以用来设定线程名、是否为daemon线程等等
- @param handler the handler to use when execution is blocked because the thread bounds and queue capacities are reached
handler 拒绝策略:当工作队列中的任务已到达最大限制,并且线程池中的线程数量也达到最大限制,这时如果有新任务提交进来,该如何处理呢。这里的拒绝策略,就是解决这个问题的,jdk中提供了4中拒绝策略
①CallerRunsPolicy
该策略下,在调用者线程中直接执行被拒绝任务的run方法,除非线程池已经shutdown,则直接抛弃任务。
②AbortPolicy
该策略下,直接丢弃任务,并抛出RejectedExecutionException异常。
③DiscardPolicy
该策略下,直接丢弃任务,什么都不做。
④DiscardOldestPolicy
该策略下,抛弃进入队列最早的那个任务,然后尝试把这次拒绝的任务放入队列