Java线程中的ThreadPoolExecutor
Java线程中的ThreadPoolExecutor是ExecutorService接口的实现类,其通过线程池中的线程来执行提交的任务。
线程池主要用来解决两个问题:一是用来解决大量异步任务导致的性能问题,它降低了每个任务调用的系统开销,二是其提供了对线程资源的管理。ThreadPoolExecutor自身维护了其一些属性,比如已完成的任务数等。
JDK提供了一些简便配置thread pool的方法:
- Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation)
- Executors.newFixedThreadPool(int) (fixed size thread pool)
- Executors.newSingleThreadExecutor() (single background thread)
如果我们要更加灵活地配置thread pool时,那么就要配置一下参数:
corePoolSize: 线程池维护线程的最少数量
maximumPoolSize:线程池维护线程的最大数量
keepAliveTime: 线程池维护线程所允许的空闲时间
unit: 线程池维护线程所允许的空闲时间的单位
workQueue: 线程池所使用的缓冲队列
handler: 线程池对拒绝任务的处理策略