线程池的超时参数

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

在ThreadPoolExecutor方法的参数注释中keepAliveTime是这样说的:

when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

就是线程数大于corePoolSize时空闲线程存活的最大时间。在方法getTask中就可明白具体是怎么实现的。

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;

            }

        }

    }

注意到工作线程数wc大于corePoolSize或allowCoreThreadTimeOut为true时timed为true。

boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

poll方法超时后timeOut变为true。

 Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;

在下一次循环中下面判断条件为真,执行了compareAndDecrementWorkerCount方法,当前线程跳出循环。

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

getTask返会null后,执行了processWorkerExit方法,当前Worker被移除。

 workers.remove(w);

你可能感兴趣的:(线程池的超时参数)