如何限制许多线程池中的线程计数?

发布于 2025-02-05 07:52:20 字数 1399 浏览 4 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

双马尾 2025-02-12 07:52:20

正如评论中指出的那样,您只需使用一个 threadpoolexecutor 就可以实现所要求的。

实际上, threadpoolexecutor 包含一个线程池,该线程的数字是根据 corepoolsize maximumpoolsize 属性调整的。 poolsize 属性代表当前正在运行的线程数或在 threadpoolpoolexecutor 中闲置。同时, corepoolSize maximumpoolsize 表示最小和最大线程创建的边界。

  • 实际上,如果提交了一个新任务,并且与 corepoolsize 正在运行的线程更少,那么即使在空闲中还有其他线程也会创建新线程。

  • 如果提交了一个新任务,并且线程的数量大于 corepoolsize ,但低于 maximumpoolSize ,则创建了一个新线程唯一b>如果队列已满;否则任务已排队。


  • 最后,如果已达到最大值时提交新任务,并且队列已满,则该任务将由默认值或提供的 recept receptedexeciTion 拒绝和处理。将调用拒绝的对象处理拒绝的方法。


在您的情况下,最多可以在15个线程中运行同样,您只需使用 newFixedThreadPool 执行人 class的方法,然后将15传递给参数,以使 corepoolsize maximumpoolSize < /code>设置为15。就像这样,您最多可以在同一执行人内同时运行15个线程。

ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(15);

As it has been pointed out in the comments, you could achieve what you're asking by using only one ThreadPoolExecutor.

In fact, a ThreadPoolExecutor contains a pool of threads whose number is adjusted according to the CorePoolSize and MaximumPoolSize properties. The PoolSize property represents the current number of threads running or in idle within the ThreadPoolExecutor. While, the CorePoolSize and MaximumPoolSize represent the bounds for minimum and maximum thread creation.

  • In fact, if a new task is submitted and fewer threads than CorePoolSize are running, a new thread is created, even if there are other threads in idle.

  • If a new task is submitted and the number of threads is greater or equal than CorePoolSize but lower than MaximumPoolSize then a new thread is created only if the queue is full; otherwise the task is queued.

  • Finally, if a new task is submitted when the MaximumCoreSize has been reached and the queue is full, then the task is rejected and handled by the default or provided RejectedExecutionHandler object which will invoke the rejectedExecution method to handle the rejection.

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html

In your case, to have at most 15 threads running at the same, you could just use the newFixedThreadPool method of the Executors class and pass 15 as the argument to have both CorePoolSize and MaximumPoolSize set to 15. Like so, you'll have at most 15 threads running at the same time within the same executor.

ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(15);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文