gpt4 book ai didi

java - Fork Join池理解

转载 作者:行者123 更新时间:2023-11-29 04:22:47 25 4
gpt4 key购买 nike

我遇到了一个来自 java.util.concurrent 包的新类 ForkJoinPool据我了解,它适用于以下场景:

将大任务分成子任务(fork),当每个任务完成后,收集所有子任务(join),然后合并。

Fork 连接池有一个构造函数public ForkJoinPool(int parallelism)
从官方文档中,我阅读了以下内容:

By splitting itself up into subtasks, each subtask can be executed in parallel by different CPUs, or different threads on the same CPU.

问题是如何设置forkjoinpool的线程数。

contructor 中的parallelism 是指线程数量还是处理器数量。如果是处理器数量,请考虑以下代码:

Runtime.getRuntime().availableProcessors()
return 4

这是否意味着以下 ForkJoinPool pool = new ForkJoinPool(8); 没有效果,因为我的 PC 只有 4 个处理器?

代码示例

public static void main(String[] args) throws Exception {

ForkJoinPool pool = new ForkJoinPool(8);
final List<String> list = Arrays.asList("dasd","dasd")//for example 300 hundrends strings;
pool.submit(()->{
list.parallelStream().forEach(AvailableProc::test);
}).get();

}

public static void test(final String code){
Thread.sleep(1000);
System.out.println(code);
}

最佳答案

Does parallelism in contructor mean the amount of threads or amount of processors

parallelism 参数告诉 ForkJoinPool 要使用多少工作线程。默认情况下,它等于可用处理器的数量,这通常是最佳的。当然,您可以在此处设置任何数字,但将其设置为大于处理器数量很可能不会受益。

Does it mean that the following ForkJoinPool pool = new ForkJoinPool(8); has no effect because my PC has only 4 processors?

这取决于你的实际任务。例如,您的代码示例将每秒打印 8 个字符串:您有 8 个线程,操作系统将使用 context switching 将所有线程调度到 4 个处理器上。 .由于大多数时间线程只是在等待,并且执行时间非常短,因此每秒可获得八个字符串。

关于java - Fork Join池理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48073809/

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