Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Jobs in Java

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

like image 239
bragboy Avatar asked Nov 28 '22 01:11

bragboy


1 Answers

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
like image 88
unholysampler Avatar answered Dec 04 '22 22:12

unholysampler