1

Possible Duplicate:
How to know if other threads have finished?

I have a threadpool that executes threads for me, how can I tell when ALL the threads I've passed it are done?

For example:

main.java

for (int i = 0; i < objectArray.length; i++) {
        threadPool.submit(new ThreadHandler(objectArray[i], i));
        Thread.sleep(500);
    }

ThreadHandler.java

public class ThreadHandler implements Runnable {

protected SuperHandler HandlerSH;
protected int threadNum;

public ThreadHandler(SuperHandler superH, int threadNum) {
    this.threadNum = threadNum;
    this.HandlerSH = superH;
}

public void run() {

    //do all methods here

}

Would I just put something into the run() section to set a boolean or something? Would I make an array of boolean to check when they're all done?

Thanks.

Community
  • 1
  • 1
A_Elric
  • 3,508
  • 13
  • 52
  • 85

1 Answers1

2

When you submit a job into a thread pool, it returns a Future instance. You can call Future.get() to see if the job has finished. This is effectively similar to a join on the tasks running in a thread pool.

You can also call threadPool.awaitTermination(...) if the thread-pool has been shutdown and you want to wait for all of the tasks have finished.

Often when I am submitting a number of jobs into a thread pool, I record their futures in a list:

List<Future<?>> futures = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
    futures.add(threadPool.submit(new ThreadHandler(objectArray[i], i)));
}
// if we are done submitting, we shutdown
threadPool.shutdown();

// now we can get from the future list or awaitTermination
for (Future<?> future : futures) {
    // this throws an exception if your job threw an exception
    future.get();
}
Gray
  • 115,027
  • 24
  • 293
  • 354