动态线程池

Dynamic Thread Pool

我有一个很长的 运行 进程来侦听事件并进行一些密集处理。

目前我使用 Executors.newFixedThreadPool(x) 来限制并发运行的作业数量,但根据一天中的时间和其他各种因素,我希望能够动态增加或减少数量并发线程。

如果我减少并发线程的数量,我希望当前的 运行 个作业能够很好地完成。

是否有 Java 库可以让我控制并动态增加或减少线程池中并发线程的数量 运行? (class 必须实现 ExecutorService)。

我必须自己实施吗?

看看下面 API 在 ThreadPoolExecutor

public void setCorePoolSize(int corePoolSize)

Sets the core number of threads. This overrides any value set in the constructor.

如果新值小于当前值,多余的现有线程将在下次空闲时终止。

如果更大,将在需要时启动新线程来执行任何排队的任务。

初始化:

ExecutorService service = Executors.newFixedThreadPool(5); 

根据需要,使用以下 API

调整线程池大小
((ThreadPoolExecutor)service).setCorePoolSize(newLimit);//newLimit is new size of the pool 

重要提示:

If the queue is full, and new value of number of threads is greater than or equal to maxPoolSize defined earlier, Task will be rejected.

因此请正确设置 maxPoolSizecorePoolSize 的值。