具有特定线程数的并行循环

时间:2015-01-01 17:48:49

标签: java multithreading

最好的方法是,如何使用指定数量的线程实现并行for循环? 像这样:

int maxThreads=5;
int curretnThreads=0;

for(int i = 0; i < 10000; i++){

   if(currentThreads<maxThreads){

      start thread...... 

   }else{
        wait...
   }

}

1 个答案:

答案 0 :(得分:2)

我首先创建一个具有固定线程数的ForkJoinPool

final ForkJoinPool forkJoinPool = new ForkJoinPool(numThreads);

现在只需在任务中执行并行流操作:

forkJoinPool.submit(() -> {
    IntStream.range(0, 10_000)
            .parallel()
            .forEach(i -> {
                //do stuff
            });
});

显然,这个例子只是简单地翻译你的代码。我建议您尽量使用Stream API而不是循环[0, 10,000)