Java多线程之ThreadPoolExecutor

线程池的作用就是使用更少的线程, 来执行更多的任务, 以达到线程的充分利用. 从ThreadPoolExecutor类的构造方法学习:

/** * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters and default rejected execution handler. * * @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 * @throws IllegalArgumentException if one of the following holds:<br> *         {@code corePoolSize < 0}<br> *         {@code keepAliveTime < 0}<br> *         {@code maximumPoolSize <= 0}<br> *         {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} *         or {@code threadFactory} is null */public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

ThreadPoolExecutor的具体执行流程有四步:

(1) 当目前执行线程的总数小于核心线程大小corePoolSize时,  提交了任务, 会立马新建一个线程来执行提交的任务.

(2) 当目前执行线程的总数达到了核心线程大小corePoolSize时, 就会将当前提交的任务存到缓存队列中

(3) 当缓存队列满了之后, 如果当前线程的总数小于maximumPoolSize时, 此时就会新建线程进行救急处理, 提交的任务会立马执行.

(4) 当线程数达到maximumPoolSize后, 就会采用拒绝策略拒绝任务

05-08 15:26