[英]How to change thread pool size in 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);
}
}
也许你可以建议我另一个线程池?
您可以使用ScheduledThreadPoolExecutor轻松做到这一点。
//Init executor
int initialPoolSize = 5;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(initialPoolSize);
//[...] do something
//Change max size
int newPoolSize = 10;
executor.setCorePoolSize(newPoolSize);
请注意,继承的方法setMaximumPoolSize(int) 对 ScheduledThreadPoolExecutor 没有影响。 要更改池大小,您需要更改 corePoolSize:
虽然这个类继承自 ThreadPoolExecutor,但一些继承的调优方法对它没有用。 特别是,因为它充当使用 corePoolSize 线程和无界队列的固定大小的池,所以对 maximumPoolSize 的调整没有任何有用的效果。 此外,将 corePoolSize 设置为零或使用 allowCoreThreadTimeOut 几乎从来都不是一个好主意,因为一旦它们有资格运行,这可能会使池没有线程来处理任务。
也许这就是您在 Executors Util 类中寻找的内容:
ExecutorService executorService = Executors.newScheduledThreadPool(5)
你可以使用setCorePoolSize(int)
方法。
同样使用Executors.newCachedThreadPool
您负责为ThreadPoolExecutor
创建线程池大小。
如果需要执行新任务, ThreadPoolExecutor
创建新线程,并使用Executors.newCachedThreadPool()
重用现有线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.