ScheduledExecutorService 具有最小和最大线程数

Swa*_*nil 1 java multithreading

我正在尝试使用 ScheduledExecutorService 在给定线程池上安排任务。

public ScheduledExecutorService scheduledExecutorService() {
    return Executors.newScheduledThreadPool(3);
}
Run Code Online (Sandbox Code Playgroud)

看起来这种创建实例的方式假定用户指定的值作为最小线程数,最大线程数为Integer.MAX_VALUE(默认值)。

如何指定 ScheduledExecutorService 实例的最大线程数?我无法分配如此巨大的线程数作为最大线程数。

反编译 jar 中的代码片段 -

// From Executors.java
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

// From ScheduledThreadPoolExecutor.java
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

// From ThreadPoolExecutor.java
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
Run Code Online (Sandbox Code Playgroud)

如果我缺少引用 Java 文档中的方法,请指出正确的位置。TIA。

小智 6

ConstructorofScheduledThreadPoolExecutor并没有直接提供该参数的设置。您可以手动调用setMaximumPoolSize方法:

    public ScheduledExecutorService scheduledExecutorService() {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize);
        scheduledThreadPoolExecutor.setMaximumPoolSize(xxx);
        return scheduledThreadPoolExecutor;
    }
Run Code Online (Sandbox Code Playgroud)

但在 中设置 thismaximumPoolSize是没有意义的ScheduledThreadPoolExecutor ,这就是为什么构造函数没有声明这个参数。

来自 Java 文档ScheduledThreadPoolExecutor

虽然该类继承自 ThreadPoolExecutor,但继承的一些调整方法对其没有用处。特别是,因为它充当使用 corePoolSize 线程和无界队列的固定大小池,所以对 MaximumPoolSize 的调整没有任何有用的效果。此外,将 corePoolSize 设置为零或使用 allowedCoreThreadTimeOut 几乎从来都不是一个好主意,因为一旦任务有资格运行,这可能会使池中没有线程来处理任务。

更多详细信息,请参阅delayedExecuteensurePrestart中的内容ScheduledThreadPoolExecutormaximumPoolSize是没有用的。

   private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            // add task to queue
            super.getQueue().add(task);
            if (isShutdown() &&
                !canRunInCurrentRunState(task.isPeriodic()) &&
                remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }

    void ensurePrestart() {
        int wc = workerCountOf(ctl.get());
        if (wc < corePoolSize)
            addWorker(null, true);
        else if (wc == 0)
            addWorker(null, false);
    }
Run Code Online (Sandbox Code Playgroud)