[英]Parallel for loop with specific number of threads
What is the best way, how to implement parallel for loop with a specified number of threads? 最佳方法是什么,如何用指定数量的线程实现并行for循环? Like this: 像这样:
int maxThreads=5;
int curretnThreads=0;
for(int i = 0; i < 10000; i++){
if(currentThreads<maxThreads){
start thread......
}else{
wait...
}
}
I would first create a ForkJoinPool
with a fixed number of threads: 我首先创建一个具有固定线程数的ForkJoinPool
:
final ForkJoinPool forkJoinPool = new ForkJoinPool(numThreads);
Now simply execute a parallel stream operation in a task: 现在,只需在任务中执行并行流操作:
forkJoinPool.submit(() -> {
IntStream.range(0, 10_000)
.parallel()
.forEach(i -> {
//do stuff
});
});
Obviously this example simply translates your code literally. 显然,此示例只是按字面意义翻译您的代码。 I would recommend that you use the Stream
API to its fullest rather than just loop [0, 10,000)
. 我建议您充分利用Stream
API,而不仅仅是循环[0, 10,000)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.