线程池原理学习

ThreadPoolExecutor线程池的构造方法中含有5个参数,第一个参数corePoolSize为核心线程数,第二个参数maximumPoolSize为所有线程数,所以非核心线程数即maximumPoolSize - corePoolSize,第三个参数keepAliveTime为非核心线程数执行完任务的存活时间,第四个参数unit为第三个参数的时间单位,第五个参数workQueue为线程池队列,源码如下图:
在这里插入图片描述

提交优先级核心线程 > 线程池队列 > 非核心线程 下图来自B站大佬
在这里插入图片描述
源码:

/**
     * 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);
        }
        // 第三个判断 如果以上两种都不执行,则执行addWorker(command, false),如果这个方法返回false 则执行拒绝策略
        else if (!addWorker(command, false))
            reject(command);
    }

执行优先级核心线程 > 非核心线程 > 线程池队列

源码:

/**
     * Main worker run loop.  Repeatedly gets tasks from queue and
     * executes them, while coping with a number of issues:
     *
     * 1. We may start out with an initial task, in which case we
     * don't need to get the first one. Otherwise, as long as pool is
     * running, we get tasks from getTask. If it returns null then the
     * worker exits due to changed pool state or configuration
     * parameters.  Other exits result from exception throws in
     * external code, in which case completedAbruptly holds, which
     * usually leads processWorkerExit to replace this thread.
     *
     * 2. Before running any task, the lock is acquired to prevent
     * other pool interrupts while the task is executing, and then we
     * ensure that unless pool is stopping, this thread does not have
     * its interrupt set.
     *
     * 3. Each task run is preceded by a call to beforeExecute, which
     * might throw an exception, in which case we cause thread to die
     * (breaking loop with completedAbruptly true) without processing
     * the task.
     *
     * 4. Assuming beforeExecute completes normally, we run the task,
     * gathering any of its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the
     * specs guarantee that we trap) and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run, we
     * wrap them within Errors on the way out (to the thread's
     * UncaughtExceptionHandler).  Any thrown exception also
     * conservatively causes thread to die.
     *
     * 5. After task.run completes, we call afterExecute, which may
     * also throw an exception, which will also cause thread to
     * die. According to JLS Sec 14.20, this exception is the one that
     * will be in effect even if task.run throws.
     *
     * The net effect of the exception mechanics is that afterExecute
     * and the thread's UncaughtExceptionHandler have as accurate
     * information as we can provide about any problems encountered by
     * user code.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            // 这个while中的判断即执行顺序,首先执行核心线程的task,如果为false再去执行非核心线程的getTask,最后才去队列里拉任务执行
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
学习C#多线程的路线可以按照以下步骤进行: 1. 先了解基本概念:开始学习之前,建议先了解多线程的基本概念和原理,包括线程、进程、并发、同步等相关概念。 2. 学习线程的创建和启动:学习如何在C#中创建和启动线程,可以使用Thread类或者Task类来实现。 3. 线程同步和互斥:学习如何在多线程环境下实现线程同步和互斥,以避免出现竞态条件和据不一致的问题。可以学习使用锁、互斥量、信号量等机制来实现线程同步。 4. 学习线程间通信:学习如何在多线程环境下实现线程间的通信,以便线程之间能够进行据交换和协作。可以学习使用共享内存、消息队列、事件等机制来实现线程间通信。 5. 学习线程池学习如何使用线程池来管理和调度线程,以提高多线程应用程序的性能和效率。 6. 学习并发集合:学习如何使用并发集合来处理多线程环境下的据共享和访问问题,包括并发队列、并发字典、并发栈等。 7. 学习异步编程:学习如何使用异步编程模型(Async/Await)来实现高效的异步操作,以提高多线程应用程序的响应性和吞吐量。 8. 学习线程安全性:学习如何编写线程安全的代码,以避免出现竞态条件和据不一致的问题。可以学习使用锁、原子操作、线程本地存储等技术来确保线程安全性。 9. 实践项目:通过实践项目来巩固所学的多线程知识,可以选择一些具有多线程需求的项目来进行实践,例如网络服务器、并发任务处理等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值