views:

226

answers:

6

Hi,

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

A: 

You need to wait on the threads to finish by using join():

// run first set of threads
List<Thread> threads = threadsList; // save reference to all threads
for(Thread t : threads){
    t.join();
}
// all threads finished

// run other set of threads
Yuval A
@Yuval: I'm not downvoting, but your join inside the loop means that it'll wait for each thread to complete before starting the next... you've serialized those 200 threads.
CPerkins
You need to join after starting them.
Justin
CPerkins - incorrect, this snippet just iterates on the threads and `join()`s them. In anycase @unholysampler has a better snippet.
Yuval A
Its ok now, he copied the working solution.
Justin
+12  A: 

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
unholysampler
code snippet please..
Bragboy
Sweet, this baby worked like a charm!
Bragboy
great - can you accept this answer then please.
joefis
Slight typo: for(Thread t : thread) should be for(Thread t : threads)
Sean Reilly
Fixed with edit.
unholysampler
+7  A: 

Feels homeworky, but ...

spawnAndWait() {
 Thread T[] = new Thread[n];
 for(int i=0;i<n;i++){
     T[i] = new Thread(runnableInstance);
     T[i].start();
 }
 for (Thread t : T) {
  t.join();
 }
}
Justin
+6  A: 

If you are using Java 1.5, use the concurrent package, if you are using Java 1.4.2, the package is still available as a backport, I am pretty sure.

That being said, I had a similar tasks to do lately; you can achieve it very easily by using ExecutorService from which you wait on the Future object to return to know whether your tasks are complete. Very clean pattern - maybe not exactly what you are trying to achieve, but in real life it works really well :-).

Some code:

BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
taskExecutor = new ThreadPoolExecutor(200, 200, 30, TimeUnit.SECONDS, workQueue);

futureList.add(taskExecutor.submit(new MyCallable()));

for (Future<Object> future : futureList) {
    future.get(); // wait for the task to complete
}

//... instantiate your second group of executors
Etienne
+1  A: 

Sort of pseudocode, you acnt instanciate callable ;-)

while( moreThreads ) {
    List<Callable<Integer>> threads = new ArrayList<Callable<Integer>>();
    for( int i = 0; i < 200; ++i ) {
        threads.add(new Callable<Integer>() );
    }

    FixedThreadPool pool = Executers.newFixedThreadPool(200);
    pool.invokeAll(threads);
    pool.shutdown();
}
InsertNickHere
A: 

Another solution is using Latch

final CountDownLatch latch = new CountDownLatch(200);

  for(int i=0; i<10; i++)
{

 Thread thread = new Thread()
{
    public void run()
{
     try{
         //do your work  

     }finally{
      latch.countDown();
     }
    }
   };

     }  
            //will block here util your threads all finished
  latch.await();
miz
Please click `edit` link and check the right column information for formatting rules :)
BalusC