线程池执行任务流程以及重用和无用非核心线程的销毁原理

ThreadPoolExexutor详解

1. execute方法(方法的入口)

图解三种情况:
在这里插入图片描述
workerCountOf:工作(活跃)线程数
isRunning:线程池状态是否处在运行

 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) {
            // 关键点:新增核心线程(Worker),true代表为核心线程
            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);
    }

2. addWorker方法(线程重用的关键)

备注:代码中标注注释了关键点

  1. w = new Worker(firstTask); newWorker代码

  2. t.start();

    1. t.start()其实调用的是w的run方法

    2. run方法调用了runWorker方法runWorker

      runWorker方法中利用循环来执行task任务,通过不断地getTask(),从阻塞对象中获取task任务执行

  3. 总结:一个addWorker方法,创建了一个线程,而这一个线程去执行runWoker方法的时候是利用while循环获取task任务来执行的,这就是为什么线程池中的每一个线程能够重用的原因,其实就是利用while循环来执行任务。

 		boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 关键点
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    // 关键点
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }

Worker(Runnable firstTask) {
    setState(-1); // inhibit interrupts until runWorker
    this.firstTask = firstTask;
    // 构造方法中初始化线程属性对象
    // this-指代当前Worker对象,而Worker类实现了Runnable接口,该thread.start()调用的run方法就是w的run方法
    this.thread = getThreadFactory().newThread(this);
}

    public void run() {
        runWorker(this);
    }

 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循环和不断地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);
        }
    }

3. getTask方法(线程池如何实现无用的非核心线程销毁操作的)

未待完结,后续补充…

  • 判断是否允许核心线程超时或者当前活动线程数是否大于核心线程数(allowCoreThreadTimeOut默认为false)
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
  • 判断当前活动线程数wc数是否大于最大线程数 || 允许超时 && 上次超时获取到的任务为null,接着判断如果wc>1,或者队列为空,则将工作线程数wc减1,并且返回一个null的task(此处就是判断是否为无用的线程的,如果无用,则在runWorker的processWorkerExit(w, completedAbruptly);这一行代码会把当前worker对象给销毁)
if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }
  • 根据timed来判断workQueue是超时等待获取队列任务,还是一直阻塞等待任务。

超时等待:当超过给定keepAliveTime时间还没有获取到任务时,则会返回null

阻塞等待:一直阻塞,直到有任务进来

Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();

private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            // Are workers subject to culling?
            // 关键点
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                // 关键点
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值