[Java]深入理解ThreadPoolExecutor的参数含义及源码执行流程

线程池:为了避免线程频繁的创建和销毁带来的性能消耗,而建立的一种池化技术,它是把已经创建的线程放入线程池中,当有任务需要执行的时候就可以重用已有的线程,不用再去创建线程,这又就可以去提高程序响应的速度。

线程池创建使用Executor和ThreadPoolExecutor的区别

一般是通过ThreadPoolExecutor创建可以规避资源耗尽的风险。Executor可能会导致OOM(内存溢出)
ThreadPoolExecutor 的核心参数:

 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:表示线程池的常驻核心线程数,这个值设计的比较小的话可能会频繁的生成或者销毁线程。设置的比较大的话可能会浪费资源,所以要根据实际情况设计。
maximumPoolSize:表示线程池任务最多时最大可以创建的线程数。官方规定这个值必须大于0,也必须大于等于corePoolSize。在任务较多时,且不能存放在任务队列的时候才会启用。
keepAliveTime:表示线程的存活时间,当线程池空闲时并且超过这个时间,多余的线程就会销毁,直到线程池中的线程数量销毁的等于corePoolSize为止,如果maximumPoolSize等于corePoolSize,那么线程池在空闲的时候也不会销毁任何线程。
unit:表示存活时间的单位,配合keepAliveTime使用。
workQueue:表示线程池执行的任务队列,当线程池的所有线程都在处理任务时,如果来了新任务就会缓存到此任务队列中排队等待执行。
threadFactory:表示线程的创建工厂,这个参数一般用的比较少,一般我们不会在创建线程池的时候指定这个参数。
RejectedExecutionHandler:表示指定线程池的拒绝策略,当线程池的任务已经在缓存队列,workQueue中存储满了,并且不能创建新的线程来执行这个任务,就会用到拒绝策略,这属于一种限流保护机制。

线程池工作流程执行方法execute():

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);
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值