Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 988
sowmya Avatar asked Apr 10 '12 16:04

sowmya


People also ask

How do you create a dynamic number of threads in Java?

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

Can multiple threads run concurrently?

Concurrency and Parallelism In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

What is dynamic multi threading?

It refers to an architecture that allows a single application to be executed in several threads dynamically. At procedure and loop borders, hardware creates profitably executed threads on a parallel multithreading pipeline. It is efficient for multiple processing.

Do threads run in parallel or concurrently?

On a single core microprocessor (uP), it is possible to run multiple threads, but not in parallel. Although conceptually the threads are often said to run at the same time, they are actually running consecutively in time slices allocated and controlled by the operating system.


Video Answer


2 Answers

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.

like image 94
Gray Avatar answered Oct 23 '22 14:10

Gray


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.

like image 3
Martin James Avatar answered Oct 23 '22 12:10

Martin James