ThreadPoolExecutor是阿里巴巴 JAVA 编码规范里面推荐的使用线程池的正确姿势

它提供了四个构造方法:

我们以最后一个构造方法(参数最多的那个),对其参数进行解释:

public ThreadPoolExecutor(int corePoolSize, // 1
                              int maximumPoolSize,  // 2
                              long keepAliveTime,  // 3
                              TimeUnit unit,  // 4
                              BlockingQueue<Runnable> workQueue, // 5
                              ThreadFactory threadFactory,  // 6
                              RejectedExecutionHandler handler ) { //7
        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;
    }
    
    
序号名称类型含义
1corePoolSizeint核心线程数,能够同时执行的任务数量
2maximumPoolSizeint除去缓冲队列中等待的任务,最大能容纳的任务 数(其实是包括了核心线程池数量)
3keepAliveTimelong超出workQueue的等待任务的存活时间,就是指maximumPoolSize里面的等待任务的存活时间
4unitTimeUnit时间单位
5workQueueBlockingQueue<Runnable>永远不会满,一般选择没有容量上限的队列
6threadFactoryThreadFactory创建线程的工厂,使用系统默认的类
7handlerRejectedExecutionHandler当任务数超过maximumPoolSize时,对任务的处理策略,默认策略是拒绝添加