Java线程池源码中最重要的部分

2024-01-15  本文已影响0人  M_lear

Java线程池里有两个东西:

  1. 若干个线程
  2. 阻塞队列

这两个东西要分开看,两者是解耦的,不能当成一个整体。

不管什么线程池。提交任务时,负责触发两块主要内容:

  1. 把任务放到阻塞队列。(这块没啥讲的)
  2. 触发线程创建(即源码里的addWorker方法)。

创建线程也没啥好讲的,关键点在于线程和阻塞队列耦合的部分(即源码里的getTask方法,这个方法是线程池源码中最最重要的部分)。

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

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

            // Check if queue empty only if necessary.
            if (runStateAtLeast(c, SHUTDOWN)
                && (runStateAtLeast(c, 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;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读