This week's book giveaway is in the Object Relational Mapping forum. We're giving away four copies of Pro JPA 2: Mastering the Java Persistence API and have Mike Keith and Merrick Schincariol on-line! See this thread for details.
for(int i=1;i<=number; i++){ String name = Integer.toString(i); MigrationWorker th = new MigrationWorker(name); th.startThread(); }
} }
Assume the MigrationWorker is a Thread Class which does some work. now i want the Parent class main method to wait till all the 10 migration workers thread are died. That means when all the 10 child threads are dead,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& will be printed.
Thanks in advance....
[ April 09, 2007: Message edited by: Purujit Saha ] [ April 09, 2007: Message edited by: Purujit Saha ]
P.S: MyThread is just a dummy Implementation. It will be replaced by the actual thread that does the work you want to do. [ April 09, 2007: Message edited by: Nitesh Kant ]
If you have JDK 1.5 or later then this should also work. There are also ways to do this with queued executor services (using Futures) if you want real thread pool management (please note the comments concerning queued executor services).
Your spawnThreads() method doesn't save any of the thread objects for the threads that it created. If it did (such as saving the objects in a collection which is returned from the method), you can later have your main thread call join() on all the thread objects, to wait for them all to complete.
Originally posted by Henry Wong: Your spawnThreads() method doesn't save any of the thread objects for the threads that it created. If it did (such as saving the objects in a collection which is returned from the method), you can later have your main thread call join() on all the thread objects, to wait for them all to complete.
Henry
Henry, firstly i am delighted to communicate with the author of the book i learned Threads from !!! Keeping aside the requirement in this problem, is it a good idea to use a wait-notify mechanism against the join paradigm? One scenario can be when threads are not computation intensive and finish their work pretty soon. So, will it be more effecient to use a wait-notify mechanism over "joining". The reason being that the parent will unnecessarily try to join even if the worker thread has already finished its job? Worth mentioning, its just a hypothetical situation for academic reasons!
join() is, in fact, implemented in Java code using wait() and notify(). The first example is just a terribly complex way of implementing Henry's suggestion by hand. If I saw code like that in a review, I'd make the author change it to use join() in a loop.