版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinaihalo/article/details/87186277
阿里编程规范不推荐Executors,通过ThreadPoolExecutor创建,明确线程池运行规则,避免资源耗尽。
Executors弊端:
FixedThreadPool和newSingleThreadExecutor,队列创建用new LinkedBlockingQueue(),允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newCachedThreadPool和ScheduledThreadPoolExecutor,允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
java源码注释和翻译
ThreadPoolExecutor方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
注释和翻译
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
在线程池中保留的线程数,即使线程空闲,除非设置allowCoreThreadTimeOut参数
@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.
当线程数超出corePoolSize,在终止前空闲线程等待新任务的时间
@param unit the time unit for the {@code keepAliveTime} argument
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.
盛放未执行任务的队列,队列只放由execute方法提交的runable任务
@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