美文网首页
Java-线程池实现线程复用和工作线程的关闭

Java-线程池实现线程复用和工作线程的关闭

作者: zzq_nene | 来源:发表于2021-02-03 22:25 被阅读0次

    1.ThreadPoolExecutor.execute

        public void execute(Runnable command) {
            if (command == null)
                throw new NullPointerException();
            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);
        }
    

    这里主要做两件事:

    • 小于corePoolSize的时候创建核心线程
    • 当前核心线程都正在执行则入队,判断是否需要创建工作线程

    2.ThreadPoolExecutor.addWorker

        private boolean addWorker(Runnable firstTask, boolean core) {
            retry:
            // 判断是否可以创建worker
            for (;;) {
                int c = ctl.get();
                int rs = runStateOf(c);
    
                // Check if queue empty only if necessary.
                if (rs >= SHUTDOWN &&
                    ! (rs == SHUTDOWN &&
                       firstTask == null &&
                       ! workQueue.isEmpty()))
                    return false;
    
                for (;;) {
                    int wc = workerCountOf(c);
                    if (wc >= CAPACITY ||
                        wc >= (core ? corePoolSize : maximumPoolSize))
                        return false;
                    if (compareAndIncrementWorkerCount(c))
                        break retry;
                    c = ctl.get();  // Re-read ctl
                    if (runStateOf(c) != rs)
                        continue retry;
                    // else CAS failed due to workerCount change; retry inner loop
                }
            }
    
            // 创建Worker并启动
            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);
            }
            return workerStarted;
        }
    

    这里采用显示锁的方式实现同步创建Worker

    3.Worker的run()

    Worker其实也是一个Runnable的子类,那么从执行到添加Worker的过程都没有线程复用的逻辑,那么该逻辑就应该是在Worker的run方法中。
    在这里可以看到,Worker的runWorker会调用ThreadPoolExecutor的runWorker方法。
    而在runWorker方法中,会采用一个while循环从task任务队列中取出待执行的任务,如果任务是没有被中断的,则会调用task.run()方法执行任务。

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

    getTask()的内部是采用一个无限for循环的方式进行循环遍历

        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);
    
                // 判断是否允许核心线程超时或者当前工作线程是否大于核心线程数
                // 如果为true
                boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
    
                if ((wc > maximumPoolSize || (timed && timedOut))
                    && (wc > 1 || workQueue.isEmpty())) {
                    if (compareAndDecrementWorkerCount(c))
                        return null;
                    continue;
                }
    
                try {
                    // 如果存在的线程数大于核心线程数,则从队列中取任务时没有任务返回null
                    // 如果存在的线程数小于核心线程数,则从队列中取任务时没有任务将阻塞队列
                    Runnable r = timed ?
                        workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                        workQueue.take();
                    if (r != null)
                        return r;
                    timedOut = true;
                } catch (InterruptedException retry) {
                    timedOut = false;
                }
            }
        }
    

    而工作线程的关闭,其实可以从上面两种情况知道,在线程通过while无限循环的时候,如果是非核心线程(即工作线程)调用BlockingQueue的poll方法,则会在队列为空的时候返回null而不会阻塞队列,当返回的task是null的时候,那么runWorker中的while循环就会退出,最终就会执行processWorkerExit(w, completedAbruptly)而completedAbruptly=false进行线程的删除;如果是核心线程的话,则会调用BlockingQueue的take()方法,那么在队列为空的时候就会通过take()方法调用而阻塞等待队列结果的返回,而不会返回一个task=null,这样runWorker中的while循环就不会退出,就会一直等待结果。

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

    所以工作线程会被关闭,而核心线程不会被关闭,就是因为工作线程的run()方法会通过task=null退出循环而执行完成run()的方法体内容,从而自动关闭;而核心线程因为阻塞等待队列返回的原因而不会导致while循环的结束,所以不会关闭。

    BlockingQueue的方法都是成对出现:
    add和remove:这两个是非阻塞的,当队列满的时候,add会抛出异常,当队列为空的时候,remove会抛出异常。
    offer和poll:使用offer往满的队列里放入元素,会返回false;poll方法往空的队列里拿元素,会返回一个null
    put和take:这是真正的阻塞方法,使用put往满的队列里放元素,会被阻塞;使用take往空的队列里拿方法,会被阻塞。

    相关文章

      网友评论

          本文标题:Java-线程池实现线程复用和工作线程的关闭

          本文链接:https://www.haomeiwen.com/subject/actvtltx.html