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();
} 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
Joined: Nov 04, 2001
Posts: 1865
posted
0
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).
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:
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi