我需要一个动态线程池的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);
}
}也许你可以建议我换一个线程池?
发布于 2019-02-11 13:58:08
您可以通过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几乎从来都不是一个好主意,因为这可能会使池没有线程来处理那些有条件运行的任务。
发布于 2019-02-11 12:54:53
也许这就是你在执行者Util类中所要寻找的:
ExecutorService executorService = Executors.newScheduledThreadPool(5)发布于 2019-02-11 14:49:09
为此,您可以使用setCorePoolSize(int)方法。
此外,使用Executors.newCachedThreadPool,您将负责为ThreadPoolExecutor创建线程池大小。
如果需要执行新任务,ThreadPoolExecutor将创建新线程,并使用Executors.newCachedThreadPool()重用现有线程。
https://stackoverflow.com/questions/54630933
复制相似问题