动态线程池 [英] Dynamic Thread Pool

查看:145
本文介绍了动态线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长时间运行的过程,它会监听事件并进行一些强烈的处理。

I have a long running process that listens to events and do some intense processing.

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

Currently I use Executors.newFixedThreadPool(x) to throttle the number of jobs that runs concurrently, but depending of the time of the day, and other various factors, I would like to be able to dynamically increase or decrease the number of concurrent threads.

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

If I decrease the number of concurrent threads, I want the current running jobs to finish nicely.

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

Is there a Java library that let me control and dynamically increase or decrease the number of concurrent threads running in a Thread Pool ? (The class must implement ExecutorService).

我是否必须自己实现它?

Do I have to implement it myself ?

推荐答案

ThreadPoolExecutor

public void setCorePoolSize(int corePoolSize)




设置核心线程数。这将覆盖构造函数中设置的任何值。

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

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

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

If larger, new threads will, if needed, be started to execute any queued tasks.

初始化:

ExecutorService service = Executors.newFixedThreadPool(5); 

根据需要,使用以下API调整线程池

((ThreadPoolExecutor)service).setCorePoolSize(newLimit);//newLimit is new size of the pool 

重要提示:


如果队列已满,并且线程数的新值大于或等于之前定义的maxPoolSize,则任务将被拒绝。

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.

因此,正确设置 maxPoolSize corePoolSize 的值。

So set values of maxPoolSize and corePoolSize properly.

这篇关于动态线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆