java 线程池执行流程源码讲解

Posted 史上最强的弟子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 线程池执行流程源码讲解相关的知识,希望对你有一定的参考价值。


threadPoolExecutor.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();
        //workerCountOf(c)获取工作线程个数是否小于核心线程数
        if (workerCountOf(c) < corePoolSize) 
        	//增加addWorker(command, true)  增加addWorker 第二个线程数是否核心
            if (addWorker(command, true))
                return;
            c = ctl.get();
        
        //如果大于核心线程数,判断是否运行,队列放入command
        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);
    

以上是关于java 线程池执行流程源码讲解的主要内容,如果未能解决你的问题,请参考以下文章

Java 并发编程线程池机制 ( 线程池执行任务细节分析 | 线程池执行 execute 源码分析 | 先创建核心线程 | 再放入阻塞队列 | 最后创建非核心线程 )

死磕 java线程系列之线程池深入解析——未来任务执行流程

深入浅出Java并发编程指南「源码分析篇」透析ThreadPoolExecutor线程池运作机制和源码体系

死磕 java线程系列之线程池深入解析——定时任务执行流程

java线程池源码的理解

通过Thread Pool Executor类解析线程池执行任务的核心流程