今天在回顾线程池的创建时,使用Executors创建线程池报错了,出现了以下问题:手动创建线程池,效果会更好哦。

查阅了阿里巴巴Java开发手册

回顾一下,通过ThreadPoolExecutor来创建。
找一下源码
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;
}
源码中我们看到了ThreadPoolExecutor的七大参数。
corePoolSize:核心线程池大小
maximumPoolSize:最大核心线程池大小
keepAliveTime:空闲线程存活时间
unit:时间单位
workQueue:阻塞队列
threadFactory:线程工厂:创建线程的,一般不用动
handler:拒绝策略
当然,还有我们要了解的四种拒绝策略。

new ThreadPoolExecutor.AbortPolicy() // 不执行新任务,直接抛出异常,提示线程池已满
new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!由调用线程处理该任务
new ThreadPoolExecutor.DiscardPolicy() //不执行新任务,也不抛出异常
new ThreadPoolExecutor.DiscardOldestPolicy() //丢弃队列最前面的任务,然后重新提交被拒绝的任务。
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());

1835

被折叠的 条评论
为什么被折叠?



