ThreadPoolExecutor参数说明
corePoolSize(核心或者常驻,比如银行有10个窗口,平常只开放5个)
maximumPoolSize(最大线程数量,银行有10个窗口)
keepAliveTime(银行有10个窗口,只开放5个,忽然来了很多人,临时开放很多接口,结束后恢复常驻线程时间)
unit - keepAliveTime (参数的时间单位)
workQueue(常驻线程用完了,就会放到阻塞队列中)
threadFactory (执行程序创建新线程时使用的工厂)
RejectedExecutionHandler (拒绝策略,银行人已经满了叫你去别的银行处理)
拒绝策略
JDK内置拒绝策略
如下代码会产生拒绝默认策略
public static void main(String[] args) throws InterruptedException {
//一池五线程
//阿里巴巴开发手册:线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式手动创建。
//Executors返回线程池对象可能会产生OOM
//corePoolSize - 池中所保存的线程数,包括空闲线程。(核心或者常驻,比如银行有10个窗口,平常只开放5个)
//maximumPoolSize - 池中允许的最大线程数。(最大线程数量,银行有10个窗口)
//keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。(银行有10个窗口,只开放5个,忽然来了很多人,临时开放很多接口,结束后恢复常驻线程时间)
//unit - keepAliveTime 参数的时间单位。
//workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。(常驻线程用完了,就会放到阻塞队列中)
//threadFactory - 执行程序创建新线程时使用的工厂。
ExecutorService executorService =new java.util.concurrent.ThreadPoolExecutor(
2,
3,
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()
);
//ExecutorService executorService = Executors.newFixedThreadPool(5);
try {
for (int i=0;i<20;i++){
executorService.execute(new Thread(() ->
System.out.println(Thread.currentThread().getName()+"办理业务")
));
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}