Java线程知识总结(二):线程池应用及原理

1、类继承关系

ThreadPoolExecutor和ScheduleThreadPoolExecutor的继承结构
(可以通过IDEA,在类中使用Ctrl + H进行查看)
在这里插入图片描述

2、ThreadPoolExecutor

2.1、ThreadPoolExecutor构造器

在这里插入图片描述
在这里插入图片描述

2.2、ThreadPoolExecutor核心方法

submit(Runnable):提交任务

	/**
     * @throws RejectedExecutionException {@inheritDoc}
     * @throws NullPointerException       {@inheritDoc}
     */
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);		//核心:调用execute方法
        return ftask;
    }

execute(task):线程池执行任务的核心方法

	/**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    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);
    }

解析:

  1. 如果线程池中,核心线程有空闲线程资源,则直接使用核心线程执行任务;
    (核心线程数:corePoolSize)
  2. 如果核心线程都在运行中,则将任务放入等待队列(workQueue);
  3. 如果等待队列已经被放满,且当前线程数少于线程池最大线程数(maximumPoolSize)时,会使用线程工厂(threadFactory)开启新的线程执行任务;
    新开启的线程不会一直存在,当达到一定时间(keepAliveTime,unit)没有执行任务(处于空闲状态)时,则线程会被销毁
  4. 如果当前线程数已经达到了线程池的最大线程数,则执行拒绝策略(handler),拒绝任务。

shutdown():终止线程池
shutdown之后不会再接受任务,直接执行拒绝策略
已经提交的任务,会继续完成,然后终止线程池

	public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
            interruptIdleWorkers();
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }

shutdownNow():立即终止线程池
与shutdown不一样的是: 正在运行中的任务,会被调用interrupted,终止线程
然后返回线程池队列的任务

	public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);
            interruptWorkers();
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

2.3、重点:如何正确设定线程池的线程数量

  • 计算型任务:cpu数量的1-2倍
  • IO型任务:要根据具体的IO阻塞时长进行考量决定,可以多开线程进行并发执行
    也可以考虑根据需要在一个最小数量和最大数量间自动增减线程数
    可以检测CPU的使用率检测线程数量是否足够。一般CPU使用率达到80%左右是最好的,如果少于80%可以多开线程,如果多于80%,说明线程数量过多,可以适当减少。

3、ScheduleThreadPoolExecutor

本质相当于把任务添加到延迟队列,即没有到达规定时间,任务无法被取出进行处理

3.1、ScheduleThreadPoolExecutor构造器

在这里插入图片描述在这里插入图片描述

3.2、ScheduleThreadPoolExecutor重要方法

schedule:相当于js的setTimeout,执行一次
scheduleAtFixedRate & scheduleWithFixedDelay
区别:
如果是间隔3秒执行一次,一个任务需要1秒,那scheduleAtFixedRate和scheduleWithFixedDelay没有区别;
不会在同一时间有并发执行,会等待
FixedRate,如果间隔1秒执行一次,但一个任务需要3秒上一个任务执行完直接开始下一次执行
FixedDelay,如果间隔1秒执行一次,但一个任务需要3秒上一次任务执行完,等待一个周期(即1秒),再进行下一次执行
根据业务流程选择,一般建议使用scheduleAtFixedRate。

4、Executors

Executors:用于创建线程池的工具类,提供多种线程池的创建方法。
不建议直接使用Executors创建线程池,但可以参考Executors的方法,使用ThreadPoolExecutor构造器创建线程池

  • newCachedThreadPool:无法预估,动态因素比较多的时候使用
    要注意,不会控制线程数量的大小,如果线程过多,也会出现卡顿
    建议自己设定最大线程数,可以设置为1000/10000,可以是一个比较大的数
    没有核心线程数,可以无限创建线程
    在这里插入图片描述
  • newFixedThreadPool
    理论上等待队列可以无限大,即不可能出现加开线程的情况。但是如果出现大量堆积的情况的话,即使加开线程也没有办法解决,应该去检查代码是否有问题。
    最大线程数和核心线程数一样,不允许加开线程,等待队列可以无限大
    在这里插入图片描述
  • newScheduleThreadPool:创建定时线程池
    在这里插入图片描述
  • newSingleThreadExecutor:创建单线程线程池
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值