创建线程池的方式:
- Executors工厂类 newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool等
- ThreadPoolExecutor 推荐
- ScheduledThreadPoolExecutor
阿里JAVA开发手册:
【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
结合最近面试的经历,发现这条建议还是十分有用的,因为自己经常使用Executors提供的工厂方法创建线程池,所以忽略了线程池内部的实现。特别是拒绝策略,面试被问到两次,因为使用Executors创建线程池不会传入这个参数而使用默认值所以我们常常忽略这一参数,还好因为这条建议,自己提前熟悉了一下ThreadPoolExecutor。
ThreadPoolExecutor讲解:
构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,