Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to wait until all threads finishes task?

 
Kamalakar Sharma
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am in process of writing a java multithread program.

Following are the steps.

1. In a method I am creating 4 threads
public void test()
{
DocThread t1 = new DocThread("one");
t1.start();
DocThread t2 = new DocThread("one");
t2.start();
DocThread t3 = new DocThread("one");
t3.start();
DocThread t4 = new DocThread("one");
t4.start();

Thread currentThread = Thread..currentThread();
try {
currentThread.sleep(10000);
}catch(Exception e) {
//do some thing
}

//do some work..

}
2. starting the above 4 threads.
3. using current thread to sleep let say 20000 in mani thread

but, what I am encountering is without waiting for all the above 4 threads the main thread exits after it sleeps for 20000?

Any one can give me better approch to wait for all the 4 threads finishes their jobs so the main thread will wait?

Thanks in Advance.
Kamal.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kamal,

Insteaad of currentThread.sleep(10000); you need,

t1.join();
t2.join();
t3.join();
t4.join();

Please look at the API to see what Thread#join() method does. In short- it waits for the thread to return (which means until the thread's run() method returns).

Regards
Maulin
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first time I read about join I did this:

That ran one at a time as I waited for each thread to finish before starting the next! Be sure to start and join in different loops:
 
Kamalakar Sharma
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Thanks for your suggestions and it worked.

I have used the following code :

t1.start();
t2.start();
t3.start();
t4.start();

synchronized(this)
{
try{
t1.join();
t2.join();
t3.join();
t4.join();
}catch(Exception e) {
//do something
}
}

The above four threads will run concorrently and the synchronized blocks will casue the main thread to wait until each thread run() methods returns.

Thanks all,
Kamalakar B.
[ December 10, 2004: Message edited by: Kamalakar Sharma ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic