Executors工具类的3种实现方式
// 单例线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 固定大小线程池
ExecutorService executorService1= Executors.newFixedThreadPool(5);
// 缓存线程池
ExecutorService executorService2 = Executors.newCachedThreadPool();
ThreadPoolExecutor七大参数
- corePoolSize:核心池大小
- maximumPoolSize:线程池最大容量
- keepAliveTime:存活时间,线程池中的线程数量大于corePoolSize,才会生效,而在此时某线程没有可执行的任务情况下,存活keepAliveTime时间之后,被销毁
- TimeUnit 存活时间的单位
- BlockingQueue:等待队列,存储等待执行的任务
- ThreadFactory:线程工厂,用于创建线程
- RejectedExecutionHandler:拒绝策略
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
4种拒绝策略
AbortPolicy:直接抛出异常
CallerRunsPolicy:谁调用谁处理
DiscardPolicy:放弃任务,不抛出异常
DiscardOldestPolicy:
尝试与等带队列中最前面的任务去争夺,不抛出异常