trouluji
trouluji

Reputation: 13

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? Like this:

int maxThreads=5;
int curretnThreads=0;

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

   if(currentThreads<maxThreads){

      start thread...... 

   }else{
        wait...
   }

}

Upvotes: 1

Views: 265

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61128

I would first create a ForkJoinPool with a fixed number of threads:

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).

Upvotes: 2

Related Questions