java - 如何更改 ScheduledExecutorService 中的线程池大小?

标签 java

我需要带有动态线程池的 ScheduledExecutorService 。我想动态更改线程池大小。我怎样才能做到这一点?

class ExecutorTask {
    private ScheduledExecutorService service;

    public void add(Task task) {
        // I need thread pool size == count added tasks.
        service.scheduleAtFixedRate(this::start, 0, 10, TimeUnit.SECONDS);
    }
}

也许你可以建议我另一个线程池?

最佳答案

您可以使用ScheduledThreadPoolExecutor轻松做到这一点.

    //Init executor
    int initialPoolSize = 5;
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(initialPoolSize);

    //[...] do something

    //Change max size
    int newPoolSize = 10;
    executor.setCorePoolSize(newPoolSize);

注意继承的方法setMaximumPoolSize(int)no effect on ScheduledThreadPoolExecutor 。要更改池大小,您需要更改 corePoolSize:

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

关于java - 如何更改 ScheduledExecutorService 中的线程池大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54630933/

相关文章:

java - 如何在场景生成器的舞台上显示不同的 fxml 文件?切换场景?

java - 更新查询,工作正常但不是我的 dao 类

java - 在终端中运行 sbt 时卡在 "Getting org.scala-sbt sbt 0.13.6 ..."

java - Spring 中的自定义标签

java - 对象内部监视器作为 java.util.concurrent.Lock

java - 将java类声明为私有(private)触发编译错误

java - 如何使用 Java 在控制台中打印任何 PostgreSQL 查询结果?

java - 查找数组中有多少个不同的值

java - 如何使用apache poi从excel读取数据并将数据存储到String[][]数组中?

Java InputMap 不注册 Shift 按键