1

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

}
3
  • 1
    "What is the best way" define "best". Commented Jan 1, 2015 at 17:54
  • @Pshemo best way= use runnable, thread class, or how? Commented Jan 1, 2015 at 17:55
  • 2
    I would say the best way is to use the Java 8 Stream API. The second best way is to use ExecutorService.fixedThreadPool. The absolute worst way is to use raw Threads. Commented Jan 1, 2015 at 17:56

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.