有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在运行时为CPUbound任务确定最佳线程数?

我正在实现一个程序,规范化一个大数据集(单个文件),这是一个数学密集型计算,因此是CPU有限的

通过查找一些最佳线程问题,大多数问题都会导致:

Runtime.getRuntime().availableProcessors()

但有了HT技术,一个内核可以同时处理两个线程

前面的一些答案还指出,最佳线程数=内核数,我不确定它是否适用于CPU有限的任务

知道每个操作系统可能会不同地执行并行编程,如果我只使用^ {CD1>},而不必考虑诸如:

  • 每个核心的线程数
  • 每个插座的磁芯
  • CPU插座

例如,我应该使用每个核心的availableProcessors()*线程来获得最佳线程吗?它会产生线程竞争吗

我正在寻找实现这一点的推荐做法,当程序移动到另一台机器时,无需修改和重建程序。(该程序仅在本地计算机上测试)

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    如果您试图为非阻塞CPU限制的任务找到最佳线程数

    Javadoc for availableProcessors()

    public int availableProcessors()
    Returns the number of processors available to the Java virtual machine.
    This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.
    
    Returns:
    the maximum number of processors available to the virtual machine; never smaller than one
    Since:
    1.4
    

    请注意,行-Returns the number of processors available to the Java virtual machine.

    由于JVM在操作系统和Java程序之间的层上运行,因此它不会返回物理处理器的数量,而是返回JVM逻辑处理器的数量。(逻辑处理器和物理处理器之间的协调取决于JVM和JVM运行的操作系统。)

    所以如果你有

    • 1CPU插槽
    • 每个插座4个
    • 每个内核2个线程

    取决于运行时环境,availableProcessors()应返回小于或等于8的整数。另一个例子:

    • 2个CPU插槽
    • 每个插座4个
    • 每个内核2个线程

    这将返回一个小于等于16的整数,具体取决于运行时环境

    因此,最佳线程数应该等于availableProcessors()。然而,要获得实际的最佳线程数,最好还是在环境中执行测试。因为您希望避免重建的复杂性,所以最好的方法可能是遵循Javadoc指令

    Javadoc中也有这样的声明: Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.

    如果希望减少线程运行开销,请查询此属性