gpt4 book ai didi

java - 在给定机器上控制 Java 线程创建的最佳方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:41 24 4
gpt4 key购买 nike

在我的应用程序中,我想根据用户的输入创建线程。例如,如果用户提供 10 个线程,我只需创建一个包含 10 个线程的池来执行某些操作。无法控制用户的输入。如果用户提供 10k 作为输入,我不想创建 10k 线程。这对机器来说是多余的。有什么建议吗?

如何控制线程池数量?
如何计算在给定机器上可以创建的最大线程数?

最佳答案

Any recommendations?

如果不对生产环境中的应用程序进行一些分析并获取一些真实的统计数据来帮助您确定实现 CPU 最大使用率的最佳条件(请参阅 Amdahl’s law ),则无法轻松实现这一目标。

也就是说,有一件事是肯定的,而且您已经知道了:创建的线程数不应多于最适合您的运行环境的数量。

Java Concurrency in Practice 进行总结:

项目 8.2 调整线程池大小

The ideal size for a thread pool depends on the types of tasks that will be submitted and the characteristics of the deployment system. Thread pool sizes should rarely be hard-coded; instead pool sizes should be provided by a configuration mechanism or computed dynamically by consulting Runtime.availableProcessors.

例如,

for compute-intensive tasks, an Ncpu-processor system usually achieves optimum utilization with a thread pool of Ncpu + 1 threads.

并给出

Ncpu = number of CPUs

Ucpu = target CPU utilization, 0 ≤ U cpu ≤ 1

W/C = ratio of wait time to compute time

The optimal pool size for keeping the processors at the desired utilization is:

(这应该回答如何计算我可以在给定计算机上创建的最大线程数?)

Nthreads = Ncpu ∗ Ucpu ∗ (1 + W/C)

您可以使用以下命令确定可用 CPU 的数量

int numberOfCPU = Runtime.getRuntime().availableProcessors();

How can I control thread pool count ?

您可以(并且应该)使用 concurrent 中的任何一个添加到 Java 中的类,而不是您自己创建和管理Thread。例如ThreadPoolExecutor .

关于java - 在给定机器上控制 Java 线程创建的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com