JDK线程池ThreadPoolExecutor学习笔记

ThreadPoolExecutor主要参数解释

/**
     * 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;
    }
  • corePoolSize 线程池中的核心线程数,即使是空闲时候,也是会保留corePoolSize的线程数。也是可以通过设置allowCoreThreadTimeOut来销毁核心线程数。
  • maximumPoolSize 最大线程数
  • keepAliveTime 当线程数大于核心线程数时,多余的空闲线程在keepAliveTime时间内可以开启新的任务,超过了则终止线程。
  • unit keepAliveTime的时间单位。TimeUnit中定义,包含一下枚举变量

        

  • workQueue 用于在任务执行前保存任务的队列。这个是BlockingQueue的子类。
  • threadFactory 执行程序创建新线程时使用的工厂。可以自定义线程工厂,设置线程的一些属性。
  • handler 拒绝策略的处理器,由于达到线程边界和队列容量而阻塞执行时使用的处理程序。

拒绝策略有:

1)AbortPolicy:拒绝任务并抛出异常RejectedExecutionException,默认的策略

2)DiscardPolicy:直接拒绝不抛出异常

3)DiscardOldestPolicy:丢弃队列中最远的一个任务(最先进入队列的,FIFO),并执行当前任务;

4)CallerRunsPolicy:只用调用者所在的线程来执行任务,不管其他线程的事。

      除了系统提供的拒绝策略外,也可以通过implements RejectedExecutionHandler自定义拒绝策略。

ThreadPoolExecutor中执行任务时候各参数的关系

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

源码中已经给出了3点各个参数之间的关系了,理解如下:

1、如果运行的线程小于corePoolSize,会启动一个新线程来执行这个任务。

2、如果运行线程大约corePoolSize,这时新任务会存放到BlockingQueue中,等待有空闲线程从BlockingQueue中取出任务执行。

3、如果有任务顺利进入queue中,这时候也是需要double check是否需要添加新线程。这是由于有可能这时候对应的线程挂了或者线程池直接被关闭了。

4、如果BlockingQueue已经满了,而corePoolSize<maximumPoolSize,这时候会尝试创建新的线程来执行任务。假如创建不成功,就可以判断线程池shut down或者是线程池已经饱和或者是直接拒绝此任务。

线程池创建corePoolSize的建议

1、创建线程池是用来执行具体任务的,任务可以细分为io密集型任务、计算密集型任务、混合型任务。

  • 对于io密集型任务,corePoolSize可以设置为CPU核心数*2
  • 对于计算密集型任务,corePoolSize可以设置未CPU核心数+1
  • 对于混合型任务,如果可以拆分为具体的不同类型的任务,就可以先拆分(这种情况应该比较少),通常简单做法可以取io和计算类型的中位数。

 

以上就是本人的一些线程池的学习体会,欢迎大神拍砖。

 

参考:

聊聊并发(三)Java线程池的分析和使用:http://ifeve.com/java-threadpool/

JDK8线程池-ThreadPoolExecutor参数:https://blog.csdn.net/fenglllle/article/details/81129125

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值