如何创建线程池?
有五种:
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; }
- corePoolSize :核心线程的数量
- maxmumPoolSize: 线程不够用时,最大的线程数
- workQueue:任务等待队列
- keepAliveTime:核心线程外的线程,不会立即被销毁,而是等待至keepAliveTime后,才被销毁
- ThreadFactory: 创建新线程
- handler:线程池的饱和策略
- AbortPolicy: 直接抛出异常,默认的策略
- CallRunsPolicy: 用调用者所在的线程来执行任务
- DiscardOldestPolicy: 丢弃队列中最靠前的任务,并执行当前任务
- DiscardPolicy: 直接丢弃任务
- 实现RejectedExecutionHandler接口的自定义handler
为什么使用线程池?
- 降低资源消耗:通过重复利用线程,降低创建线程和销毁线程的消耗
- 提高线程的可管理型:统一分配、调优和监控
线程池的状态:五种
线程池的大小如何选定?
- CPU密集型:线程数 = CPU核数 +1
- IO密集型:线程数 = CPU核数 *(1+平均等待时间/平均工作时间)