I want to spawn 200 threads simultaneously in Java. What I'm doing right now is running into a loop and creating 200 threads and starting them. After these 200 gets completed, I want to spawn another 200 set of threads and so on.
The gist here is that the first 200 threads I spawned need to be FINISHED before spawning the next set. I tried the code below, but its not working
for(int i=0;i<200;i++){
Thread myThread = new Thread(runnableInstance);
myThread.start();
}
for(int i=0;i<200;i++){
Thread myThread = new Thread(runnableInstance);
myThread.start();
}
Note: I have intentionally put the for loop Twice, but the desired effect I intend is not happening simply because the second for loop is executed before the first set of threads end their execution.
Please advise
You should keep a list of the threads you have created. Then once you have started all of them, you can loop over the list and perform a join
on each one. When the join loop finishes, all of your threads will have run to completion.
List<Thread> threads = new List<Thread>();
for(int i=0;i<200;i++){
Thread myThread = new Thread(runnableInstance);
myThread.start();
threads.add(myThread);
}
//All threads are running
for(Thread t : threads) {
t.join();
}
//All threads are done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With