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