Creating dynamic number of threads concurrently

java, multithreading, parallel-processing

Solution

But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel.

You can certainly create an array of threads using a loop:

 Thread[] threads = new Thread[NUM_JOBS_TO_CREATE];
 for (int i = 0; i < threads.length; i++) {
     threads[i] = new Thread(new Runnable() {
         public void run() {
             // some code to run in parallel
             // this could also be another class that implements Runnable
         }
     });
     threads[i].start();
 }

This will cause the threads to run in the background in parallel. You can then join with them later to wait for them all to complete before continuing.

// wait for the threads running in the background to finish
for (Thread thread : threads) {
    thread.join();
}

But instead of managing the threads yourself, I would recommend using the builtin Java `Executors`. They do all of this for you are are easier to manage. One of the benefits of this method is that it separates the tasks from the threads that run them. You can start, for example, 10 threads to run 1000s and 1000s of tasks in parallel.

Here's some sample `ExecutorService` code:

 // create a pool of threads, 10 max jobs will execute in parallel
 ExecutorService threadPool = Executors.newFixedThreadPool(10);
 // submit jobs to be executing by the pool
 for (int i = 0; i < NUM_JOBS_TO_CREATE; i++) {
    threadPool.submit(new Runnable() {
         public void run() {
             // some code to run in parallel
             // this could also be another class that implements Runnable
         }
     });
 }
 // once you've submitted your last job to the service it should be shut down
 threadPool.shutdown();
 // wait for the threads to finish if necessary
 threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

For more info, see the Java tutorial on the thread executors.

Problem

Each time I have to create a variable number of threads. I do this by creating an array of Threads and create multiple number of threads. But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel. Please guide if what to do in this senario.

Original source