Waiting for all threads to end in Java

Looking in Google for some easy out-of-the-box way for waiting for all threads to end and then continue the main() (or something) method, I found that no simple way was indicated anywhere. Use thread.join(). Yeah sure, only problem is that I have multiple threads and I want all of them to run and time the running time.

For example: I have 4 threads:

Thread t1,t2,t3,t4;

which I run from a main() method in a Java class. The main method looks like this:

public void main(String[] args) {
… some stuff before

// first run
t1.start();
t2.start();
t3. start();
t4.start();

// second run
t1.start();
t2.start();
t3. start();
t4.start();
}

Now I want to not start the second run before the first is over. A way to do this, is by running:

public void main(String[] args) {
… some stuff before

// first run
t1.start();
t2.start();
t3. start();
t4.start();

// wait till all of these are done
t1.join();
t2.join();
t3. join();
t4.join();
… etc

For this trivial case, this is ok, but in the real program I am writing, a lot of threads are started, for instance from classes.methods all over the place, making keeping references to them for joining quite a challenge.

Anyway; Google did not indicate to me a straight, simple and generic way of doing it, so I did the following:

class ThreadCheck extends Thread {
List l = new ArrayList();

public void queueThread(Thread t) {
l.add(t);
}

public void run() {
for (int i=0;i<l.size();i++) {
try {
l.get(i).join();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Now you can add your Threads to the object;

tc=ThreadCheck();
t1.start();
tc.queueThread(t1);t2.start();
tc.queueThread(t2);
etc

I usually pass tc to the the Thread when creating it, so it can queue itself after it is started; this makes it even easier, because you don’t need any references to the threads after creation.Then you can start the tc;

tc.start();

and make sure all ends only when all threads are done:

tc.join();

To time the execution:

long st= System.currentTimeMillis();itc.start(); tc.join();
long et= System.currentTimeMillis()-st;
System.out.println(“Stuff ran for “+et+” milliseconds”);

The above method works very well, but if anyone knows a better method, please mail me!

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>