有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解ThreadPoolExecutor中的池大小

我浏览了ThreadPoolExecutor类的execute方法。这似乎非常简短和简单:

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        }
        else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    }
}

但是,如果条件poolSize >= corePoolSize得到满足,似乎什么也不会发生

因为如果OR条件的第一部分为true,则第二部分将不会执行:

if (true || anyMethodWillNotBeExecuted()) { ... }

根据the rules for thread creation,这里还有maximumPoolSize。如果线程数等于(或大于)corePoolSize且小于maxPoolSize,则应为任务创建新线程或将任务添加到队列中

那么为什么在poolSize大于或等于corePoolSize的情况下什么都不应该发生呢


共 (1) 个答案

  1. # 1 楼答案

    addIfUnderCorePoolSize将为此执行器创建一个新的“核心”线程。 如果执行器(poolSize)中的线程数已经大于或等于“核心”线程数(corePoolSize),则显然不需要创建更多的“核心”线程

    也许扩展OR条件会更清楚一些:

    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        if (poolSize >= corePoolSize) {
            // there are enough core threads
            // let's try to put task on the queue
            if (runState == RUNNING && workQueue.offer(command)) {
                if (runState != RUNNING || poolSize == 0)
                    ensureQueuedTaskHandled(command);
            } else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated
        } else if (addIfUnderCorePoolSize(command)) {
            // there was not enough core threads, so we started one
            // the task is being executed on a new thread, so there's nothing else to be done here
            return;
        } else {
            // there are enough core threads
            // but we could not start a new thread
            // so let's try to add it to the queue
            if (runState == RUNNING && workQueue.offer(command)) {
                if (runState != RUNNING || poolSize == 0)
                    ensureQueuedTaskHandled(command);
            } else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated
        }
    }