views:

1146

answers:

5

Across the course of my programs execution a number of threads are started, the amount varies depending on user defined settings but they are all running the same method with different variables.

In some situations, a clean up is required mid execution, part of this is stopping all the threads, I don't want them stop immediately though, I just set a variable that they check for that terminates them. The problem is that it can be up to 1/2 second before the thread stops but before the clean up continues I need to be sure that all threads have stopped. The cleanup is executed from another thread so really I need this thread to wait for the others.

I have though of several ways of doing this but they all seem to be overly complex. I was hoping there would be some method that can wait for a group of threads to complete. Does anything like this exist?

Thanks.

+10  A: 

Just join them one by one:

for (Thread thread : threads) {
  thread.join();
}

(You'll need to do something with InterruptedException, and you may well want to provide a time-out in case things go wrong, but that's the basic idea...)

Jon Skeet
Thanks, this seems to work, had to refactor my code a little to get the thread references in my cleanup method but I think it is working. It is running now, just takes a few minutes.
Android
Just completed testing it. Worked perfectly.
Android
+3  A: 

Define a utility method (or methods) yourself:

public static waitFor(Collection<? extends Thread) c) throws InterruptedException {
    for(Thread t : c) t.join();
}

Or you may have an array

public static waitFor(Thread[] ts) throws InterruptedException {
    waitFor(Arrays.asList(ts));
}

Alternatively you could look at using a CyclicBarrier in the java.util.concurrent library to implement an arbitrary rendezvous point between multiple threads.

oxbow_lakes
+4  A: 

If you are using java 1.5 or higher, you can try CyclicBarrier. You can pass the cleanup operation as its constructor parameter, and just call barrier.await() on all threads when there is a need for cleanup.

Tadeusz Kopec
Thanks, this seems like it would do what I want but had already written Jon's answer when I saw this.
Android
An alternative, if you are only doing this once, is to use CountdownLatch.
Dan Dyer
+1  A: 

for (Thread thread : threads) { thread.join(); }

Check this code .This will work.

prakash.panjwani
+2  A: 

Have you seen the Executor classes in java.util.concurrent? You could run your threads through an ExecutorService. It gives you a single object you can use to cancel the threads or wait for them to complete.

Kenster