美文网首页
Java线程池源码中最重要的部分

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

作者: M_lear | 来源:发表于2024-01-15 14:00 被阅读0次

    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;
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Java线程池源码中最重要的部分

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