【问题标题】:How can I tell if a thread is finished? [duplicate]如何判断一个线程是否完成? [复制]
【发布时间】:2013-01-14 11:40:12
【问题描述】:

可能重复:
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() 部分中添加一些东西来设置布尔值或其他东西?我会创建一个布尔数组来检查它们什么时候都完成了吗?

谢谢。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    当您将作业提交到线程池时,它会返回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();
    }
    

    【讨论】:

    • futures 在您的示例中不会为空吗?您似乎从未在列表中添加任何内容。
    • 我认为他的意思是在他的第一个循环中执行 futures.add?
    • 哎呀。正确的。固定的。谢谢大家。
    猜你喜欢
    • 2014-07-19
    • 2019-08-28
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2014-01-06
    相关资源
    最近更新 更多