2

In Java you can use Thread.join() to wait for a thread to exit

Is there a similar method that will allow you to wait for any thread in a list of threads to exit?

This would be similar to the wait(2) Unix system call that returns when any child process exits.

Mike
  • 58,961
  • 76
  • 175
  • 221
  • 2
    Use an `Executor` of some kind and call `invokeAll`, which will block until all tasks have been completed – MadProgrammer Aug 03 '14 at 04:25
  • here is the [code](http://stackoverflow.com/questions/24981726/simultaneously-processing-in-one-servlet/24981776#24981776) using CoundDownLatch. – Braj Aug 03 '14 at 04:29
  • 1
    I don't quite understand this from a *design* perspective. wait for *any* thread. Suppose you start 5 threads, you want to wait for *any* thread to exit?. `CountdownLatch` could indeed be used, you could set the count to `1` initially and decrement the count in all the threads, but why? – TheLostMind Aug 03 '14 at 04:30

4 Answers4

4

You could use a CountDownLatch from the java.util.concurrent package. Something like this:

CountDownLatch c = new CountDownLatch(3);
...
c.await();
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Look at CountDownLatch if you are using Java 1.5 or above

shazin
  • 21,379
  • 3
  • 54
  • 71
0

Suppose you need to submit a set of background tasks, and you want to wait for each one to become available and process its result, but you don't want to block waiting for all of them before you start processing. You can use an ExecutorCompletionService.

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public final class Main {

    public static void main(String[] args) throws Exception {
        // Bootstrap CompletionService backed by a pool of 5 daemon threads.
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(
            Executors.newFixedThreadPool(5, new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setDaemon(true);
                    return t;
                }
            }));

        // Submit 20 contrived Callables that just return a monotonically
        // increasing integer.  Introduce a random sleep just to make the
        // multi-threading effects more visible.
        int n = 20;
        for (int i = 0; i < n; ++i) {
            final Integer result = i;
            // The submit call does not block here.
            cs.submit(new Callable<Integer>() {
                @Override
                public Integer call() {
                    try {
                        Thread.sleep((long)(Math.random() * 10));
                        return result;
                    } catch (InterruptedException e) {
                        return null;
                    }
                }
            });
        }

        for (int i = 0; i < n; ++i) {
            // The take call blocks here until the next Callable finishes.
            Integer result = cs.take().get();
            if (result != null) {
                System.out.println(result);
            }
        }
    }
}
Chris Nauroth
  • 9,614
  • 1
  • 35
  • 39
0

CountdownLatch is nice, but a Semaphore is re-useable.

final Semaphore semaphore = new Semaphore(0);

class WaitedForTask implements Runnable {
    @Override
    public void run() {
        try {
            doSomethingUseful();
        } finally {
            semaphore.release();
        }
    }
}

void runnem() throws InterruptedException {
    Thread[] thread = new Thread[NUMTHREADS];
    for (int i=0 ; i<NUMTHREADS ; i++) {
        thread[i] = new Thread(new WaitedForTask());
        thread[i].start();
    }
    for (int i=0 ; i<NUMTHREADS ; i++) {
        semaphore.acquire();
        System.out.println("Another one bites the dust.");
    }
}
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57