三大方法
Executor:
- newSingleThreadExecutor()//单个线程
- newFixedThreadPool()//固定线程池大小
- newCachedThreadPool()//可伸缩大小的线程池
本质ThreadPoolExecutor()
七大参数
public ThreadPoolExecutor(int corePoolSize,//1:核心
int maximumPoolSize,//2最大
long keepAliveTime,//3超时等待,
TimeUnit unit,//4
BlockingQueue<Runnable> workQueue,//5阻塞队列
ThreadFactory threadFactory,//6线程工厂
RejectedExecutionHandler handler) {//7拒绝策略
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;
}
建议不要使用Executors
去创建,规避资源耗尽的风险,而通过ThreadPoolExecutor
的方式,这样能够让我们更能了解线程池的运行规则
四种拒绝策略