线程学习三:线程池ThreadPoolExecutor 与 Executors






/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @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
     * @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} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
            int maximumPoolSize,
             long keepAliveTime,
            TimeUnit unit,
            BlockingQueue<Runnable> workQueue,
            ThreadFactory threadFactory,
            RejectedExecutionHandler handler) {
        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;
    }
<pre name="code" class="java">/**
     * Set containing all worker threads in pool. Accessed only when
     * holding mainLock.
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();




 ThreadPoolExecutor 类的逻辑处理集中在8个属性上面,上面是8个属性构造源码 

workers           : 线程池 ,Worker是其内部类,没个Worder含有一个线程

corePoolSize  : 线程池中最小活动线程

maximumPoolSize  :  线程池中最大允许线程数

workQueue :  缓存队列

keepAliveTime  : 线程池中空闲线程最大存活时间

TimeUnit : keepAliveTime的单位

threadFactory  :  新建线程时工厂类

handle : 处理被拒绝线程的处理类

执行过程,如我们上篇的图,也如上面源码中的英文注释 (至于执行源码,有点地方还没弄通,就不写分析了)

当新来任务的时候,

1、如果线程池小于corePoolSize , 那么新建线程执行该任务

2、如果线程池大于等于corePoolSize , 那么就往workQueue中添加

3、如果workQueue满了且线程池小于maximumPoolSize ,那么就新建线程执行任务

4、如果workQueue满了且线程池等于maximumPoolSize  ,那么就拒绝任务 。

至于缓存中的线程是如何执行的呢 ?

在每个新建线程中都有这么一段等效代码 加在原任务执行结束后:

while(  task = workQueue.poll(keepAliveTime ,TimeUnit ) ) {task.run();}

即线程执行任务完后会最大阻塞等待keepAliveTime 时间,直到从缓存队列workQueue中获取任务 (这段时间内称线程为闲置线程)。

获取到新任务就执行,没获取到,那么线程结束。

至于常见的Executors中的几个构建对象源码如下,大家自己理解喽:

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }//无限缓存,有nThreads个线程能够并发执行任务,闲置时间为0 ,即执行完任务瞬间找不到新任务就关闭线程

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    } //无限缓存,只有一个线程顺讯的执行放进来的任务,闲置时间为0,即执行完任务瞬间找不到新任务就关闭线程

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    } //0缓存,每新来个任务都看是否有闲置线程,有就使用闲置线程执行,否则新建线程 。 线程最大闲置时间60s


一般情况上诉3个已经满足,如果大家另有需求就自行构建喽 。

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(5, 10,
                                    1L, TimeUnit.SECONDS,
                                    new ArrayBlockingQueue<Runnable>(5)));
    }








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值