简体   繁体   English

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

[英]How to change thread pool size in ScheduledExecutorService?

I need ScheduledExecutorService with a dynamic thread pool.我需要带有动态线程池的 ScheduledExecutorService。 I want to change the thread pool size dynamically.我想动态更改线程池大小。 How can I do this?我怎样才能做到这一点?

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

Maybe you can advice me another thread pool?也许你可以建议我另一个线程池?

You can easily do that with ScheduledThreadPoolExecutor .您可以使用ScheduledThreadPoolExecutor轻松做到这一点。

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

    //[...] do something

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

Note that the inherited method setMaximumPoolSize(int) has no effect on ScheduledThreadPoolExecutor .请注意,继承的方法setMaximumPoolSize(int) 对 ScheduledThreadPoolExecutor 没有影响 To change the pool size you need to change the corePoolSize:要更改池大小,您需要更改 corePoolSize:

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it.虽然这个类继承自 ThreadPoolExecutor,但一些继承的调优方法对它没有用。 In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect.特别是,因为它充当使用 corePoolSize 线程和无界队列的固定大小的池,所以对 maximumPoolSize 的调整没有任何有用的效果。 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.此外,将 corePoolSize 设置为零或使用 allowCoreThreadTimeOut 几乎从来都不是一个好主意,因为一旦它们有资格运行,这可能会使池没有线程来处理任务。

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

ExecutorService executorService = Executors.newScheduledThreadPool(5)

you can use setCorePoolSize(int) method for that.你可以使用setCorePoolSize(int)方法。

Also using Executors.newCachedThreadPool you provide the responsibility of creating the thread pool size to ThreadPoolExecutor .同样使用Executors.newCachedThreadPool您负责为ThreadPoolExecutor创建线程池大小。

The ThreadPoolExecutor creates new threads if needed to execute the new tasks, and reuses the existing ones with Executors.newCachedThreadPool()如果需要执行新任务, ThreadPoolExecutor创建新线程,并使用Executors.newCachedThreadPool()重用现有线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM