如何判断线程是否完成?

时间:2013-01-30 15:33:41

标签: java multithreading

  

可能重复:
  How to know if other threads have finished?

我有一个为我执行线程的线程池,如何判断我传递完所有线程的时间?

例如:

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

}

我会在run()部分放置一些东西来设置布尔值或其他东西吗?我是否会制作一个布尔数组来检查它们何时完成?

感谢。

1 个答案:

答案 0 :(得分:2)

当您将作业提交到线程池时,它会返回Future instance。您可以致电Future.get()查看作业是否已完成。这实际上类似于在线程池中运行的任务的连接。

如果线程池已关闭并且您想等待所有任务完成,您也可以调用threadPool.awaitTermination(...)

通常当我向线程池提交大量作业时,我会将他们的未来记录在列表中:

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();
}