动态线程池

编程入门 行业动态 更新时间:2024-10-27 08:26:03
本文介绍了动态线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

动态线程池

本文发布于:2023-11-24 11:41:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!