sowmya
sowmya

Reputation: 181

Creating dynamic number of threads concurrently

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.

Upvotes: 15

Views: 41362

Answers (5)

Saneth
Saneth

Reputation: 31

Scanner reader = new Scanner(System.in);
    System.out.println("Enter a positive number: ");
    int n = reader.nextInt();
    if(n>0){
        Thread[] ob = new Thread[n];
        for (int i = 0; i < ob.length; i++) {
            int num = i+1;
            ob[i] = new Thread(new Runnable() {
         public void run() {
             System.out.println("Hello, I am Thread #"+num);
         }
            });
            ob[i].start();
        }
    }else{
        System.out.println("Please Enter A Positive Integer");
    }

Upvotes: 0

Stuart Cardall
Stuart Cardall

Reputation: 2457

In a class that needs to be multithreaded I set at the top of the class:

private static final ExecutorService executor = Executors.newCachedThreadPool();

& in Java 8+ use a lamda expression wherever I need something to run in a new thread:

executor.submit(() -> {
        myOtherClass.myFunction(doSomething);
});

With a newCachedThreadPool Java will manage the total number of threads according to the number of cpu cores on the system & automatically stop them after a period of inactivity (60 seconds by default).

Upvotes: 2

Gray
Gray

Reputation: 116908

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.

Upvotes: 38

Martin James
Martin James

Reputation: 24877

Try very hard to not create arrays of threads and attempt to manage them - it will soon turn in to an apalling mess. If you need a pool of threads to run tasks, you need a producer-consumer queue. Create one and pass it, (or the threadpool object instance that contains it as a member), into the threads as you create them. The threads loop round, fetching tasks and executing them.

The easy way to do this is to use an ExecutorService as detailed by @Gray, (+1).

For emphasis, I say again, don't try to micro-manage threads in arrays, lists or vectors, starting them, checking their state in a 'boss/management' loop, terminating/aborting them, destroying them etc. etc. It's like a Porsche 911 - after the expenditure of a huge amount of money/time to get one, you will have something that seems to work OK and then it will suddenly break and spin you into a tree.

Use a dedicated thread for jobs that block for extended periods, a threadpool for those that can be done intensively and quickly.

Upvotes: 3

Hunter McMillen
Hunter McMillen

Reputation: 61520

Basic psuedocode:

create x threads, store them in an array or list;
for each thread in the list/array
   call start() on the thread object;

Upvotes: 2

Related Questions