为什么须要调用ThreadPoolExecutor构造方法去创立线程池,因为阿里巴巴开发手册如是说:
那咱们先理解下ThreadPoolExecutor构造方法的七个参数代表什么。
ThreadPoolExecutor类的源码如下:
/** * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters. * * @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. * @param threadFactory the factory to use when the executor * creates a new thread * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @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} * or {@code threadFactory} or {@code handler} is null */ 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; }
其实源码中办法上的正文曾经很分明了(浏览源码正文是个很好的习惯),咱们这里简略翻译下:
corePoolSize: 外围线程数,即始终保留在线程池当中的线程数量,即便没有工作须要解决。
maximumPoolSize: 最大线程数,以后线程池中容许创立的最大线程数。
keepAliveTime:存活工夫,大于外围线程数的线程期待新工作的最长工夫,这个工夫内没有新工作须要解决,则销毁这个线程
unit:存活工夫的单位,TumeUnit类,有NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS选项
workQueue:工作队列。用于在执行工作之前保留工作的队列。 此队列将仅保留由 execute 办法提交的 Runnable 工作。当有新工作来时,首先判断沉闷的线程是否小于外围线程数,如果小于,则新增线程直到等于外围线程数,再后续则判断当前任务队列是否曾经满员,如果未满,退出队列等待执行,如果已满则开启新的线程。如果线程数达到最大线程数,则执行回绝策略(第七个参数)
threadFactory:执行器创立新线程时应用的工厂,默认DefaultThreadFactory
handler:回绝策略RejectedExecutionHandler。默认AbortPolicy
咱们能够看到实现RejectedExecutionHandler的实现类有四个:
见名知意咱们简略了解下:
AbortPolicy:停止策略,针对满员后的新工作间接抛出RejectedExecutionException异样
CallerRunsPolicy: 由以后线程次所在的线程去执行被回绝的新工作。
DiscardPolicy:抛弃策略,空办法什么都不干,等于间接疏忽了新工作,不执行然而也不抛出异样。
DiscardOldestPolicy:抛弃最早的策略。当工作被回绝是,会摈弃工作队列中最旧的工作也就是最先退出队列的,再把这个新工作增加进去。e.getQueue().poll();
/* Predefined RejectedExecutionHandlers */ /** * 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 { /** * Creates a {@code CallerRunsPolicy}. */ public CallerRunsPolicy() { } /** * Executes task r in the caller's thread, unless the executor * has been shut down, in which case the task is discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); } } } /** * A handler for rejected tasks that throws a * {@code RejectedExecutionException}. */ public static class AbortPolicy implements RejectedExecutionHandler { /** * Creates an {@code AbortPolicy}. */ public AbortPolicy() { } /** * Always throws RejectedExecutionException. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task * @throws RejectedExecutionException always */ 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 { /** * Creates a {@code DiscardPolicy}. */ public DiscardPolicy() { } /** * Does nothing, which has the effect of discarding task r. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ 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 { /** * Creates a {@code DiscardOldestPolicy} for the given executor. */ public DiscardOldestPolicy() { } /** * Obtains and ignores the next task that the executor * would otherwise execute, if one is immediately available, * and then retries execution of task r, unless the executor * is shut down, in which case task r is instead discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } }
理解了上述七个参数后,咱们再看看阿里云标准中不提倡的线程池对象:
FixedThreadPool
/** * FixedThreadPool是外围线程和最大线程一样,然而队列没指定容量,默认是MAX_VALUE。所有能够始终创立新工作,导致OOM */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public LinkedBlockingQueue() { this(Integer.MAX_VALUE); }
SingleThreadExecutor
/** * SingleThreadExecutor是单个线程,然而队列没指定容量,默认是MAX_VALUE。所有能够始终创立新工作,导致OOM */ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
CachedThreadPool
/** * CachedThreadPool最大线程是是MAX_VALUE,默认的队列是SynchronousQueue,是阻塞的。所以有新工作来就会创立新的线程,导致OOM */public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
ScheduledThreadPool
/** * CachedThreadPool最大线程是是MAX_VALUE,队列是DelayedWorkQueue默认长度为16。所以能够始终创立新的线程,导致OOM */ public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }