有 Java 编程相关的问题?

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

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

我需要带有动态线程池的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);
    }
}

也许你能给我建议另一个线程池


共 (3) 个答案

  1. # 1 楼答案

    你可以用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.

  2. # 2 楼答案

    也许这就是您在Executors Util类中寻找的:

    ExecutorService executorService = Executors.newScheduledThreadPool(5)
    
  3. # 3 楼答案

    您可以使用setCorePoolSize(int)方法来实现这一点

    还可以使用Executors.newCachedThreadPool将线程池大小创建为ThreadPoolExecutor

    如果需要执行新任务,ThreadPoolExecutor会创建新线程,并使用Executors.newCachedThreadPool()重用现有线程