线程池 类 接口 粗览

—> Executor 最顶部接口

—> ExecutorService extends Executor

—> AbstractExecutorService implements ExxecutorService

—> ThreadPoolExecutor extends AbstractExecutorService

Executors –> 这个类有多个创建线程池的静态工厂方法

public static ExecutorService newCachedThreadPool(...参数略) {
        return new ThreadPoolExecutor(参数略...);
}
...

newFiexedThreadPool(int Threads):创建固定数目线程的线程池。

newCachedThreadPool():创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果没有可用的线程,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。

newSingleThreadExecutor()创建一个单线程化的Executor。

newScheduledThreadPool(int corePoolSize)创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

静态工厂方法只是对实际创建线程池的方法的封装…

特别的,

public static ExecutorService newWorkStealingPool() {
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
}

这是 jdk 1.8 引入的,内部构建 ForkJoinPool,利用 WorkSteaLing 算法…

不过 [阿里巴巴 Java 开发手册] 中不建议(不允许)使用 Executors 创建线程池.

通过 ThreadPollExecutor 创建,这样可以让开发者更明确线程池的运行规则,避免资源耗尽的风险.

创建线程池 核心参数

能看到,核心是 ThreadPoolExecutor 这个类…

看看它的构造方法…

 /**
 *
 * @param corePoolSize the number of threads to keep in the pool, even
 *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
 * @param maximumPoolSize the maximum number of threads to allow in the
 *        pool
 * @param keepAliveTime when the number of threads is greater than
 *        the core, this is the maximum time that excess idle threads
 *        will wait for new tasks before terminating.
 * @param unit the time unit for the {@code keepAliveTime} argument
 * @param workQueue the queue to use for holding tasks before they are
 *        executed.  This queue will hold only the {@code Runnable}
 *        tasks submitted by the {@code execute} method.
 * @param threadFactory the factory to use when the executor
 *        creates a new thread
 * @param handler the handler to use when execution is blocked
 *        because the thread bounds and queue capacities are reached
 */
public ThreadPoolExecutor(int corePoolSize,//核心线程数
                          int maximumPoolSize,//最大线程数
                          long keepAliveTime,//闲置线程的存活时间
                          TimeUnit unit,//keepAliveTime 的时间单位
                          BlockingQueue<Runnable> workQueue,//线程队列
                          ThreadFactory threadFactory,//线程工厂
                          RejectedExecutionHandler handler) {//达到线程池容量和队列容量的处理策略(拒绝任务的处理策略)
}

拒绝任务的处理策略

RejectedExecutionHandler 提供了四种方式来处理任务拒绝策略

1、直接丢弃(DiscardPolicy)

2、丢弃队列中最老的任务(DiscardOldestPolicy)

3、抛异常(AbortPolicy)

4、将任务分给调用线程来执行(CallerRunsPolicy)