G
Gary J
I have a java program that spawns a lot of threads to process a very large
tree data model. How do I force a "parent" thread to wait until all of its
"child" threads are finished.
Here's a totally contrived example. TreeCounter simply counts the elements
in a tree of Elements:
public class TreeCounter
{
private int count;
void countChildren(Element element)
{
count++;
List children = element.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext()
{
Element child = iter.next();
new Thread()
{
public void run()
{
countChildren(child)
}
}.start();
}
// wait for all threads created by addChild() to finish before returning
// print out results
System.out.println(count + "elements processed");
}
}
This code was written just for this post so there may be some errors but you
get the idea.
In the above code, each incarnation of countChildren() can create multiple
threads.
How can I ensure that I don't get to the println() statement before all the
threads have finished? I know I can make threads run one at a time by
making a method "synchronized" but here I really want to make sure they all
run at the same time;
Thanks
tree data model. How do I force a "parent" thread to wait until all of its
"child" threads are finished.
Here's a totally contrived example. TreeCounter simply counts the elements
in a tree of Elements:
public class TreeCounter
{
private int count;
void countChildren(Element element)
{
count++;
List children = element.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext()
{
Element child = iter.next();
new Thread()
{
public void run()
{
countChildren(child)
}
}.start();
}
// wait for all threads created by addChild() to finish before returning
// print out results
System.out.println(count + "elements processed");
}
}
This code was written just for this post so there may be some errors but you
get the idea.
In the above code, each incarnation of countChildren() can create multiple
threads.
How can I ensure that I don't get to the println() statement before all the
threads have finished? I know I can make threads run one at a time by
making a method "synchronized" but here I really want to make sure they all
run at the same time;
Thanks