等待所有线程完成其工作,然后测量经过的时间 [英] Wait for all the threads to finish their job and then measure the time elapsed

查看:49
本文介绍了等待所有线程完成其工作,然后测量经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多线程代码之一中使用了 Executor服务.我试图查看我所有的线程是否都完成了工作,然后再执行某些任务.

I am using Executor service in one of my Multithreaded code. I am trying to see whether all of my threads are finished doing their job then afterwards I need to do certain task.

当前,我需要测量经过的时间,因此仅在所有线程完成执行该作业后,才能测量经过的时间.所以我目前有这个代码吗?我正在测量 finally块中的经过时间.

Currently I need to measure the time elapsed, so I can only measure the time elapsed only after all the threads has finished executing there job. So I have this code currently? And I am measuring time elapsed in the finally block.

ExecutorService service = Executors.newFixedThreadPool(noOfThreads);

long startTime = System.nanoTime();
try {
    for (int i = 0; i<noOfThreads; i++) {
        service.submit(new Task());
    }
    service.shutdown();
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

    //Do I need this while block here?
    while (!service.isTerminated()) {

    }
} catch (InterruptedException e) {
    //Log exception here
} finally {
    long estimatedTime = System.nanoTime() - startTime;
    logTimingInfo(estimatedTime, noOfTasks, noOfThreads);
}

我不确定在这里是否需要 while循环?我目前的做法是否正确?

I am not sure whether I need while loop here or not? Is the way I am currently doing it right or not?

更新的代码:-

因此下面的代码应该可以正常工作.对吧?

So below code should work fine. Right?

ExecutorService service = Executors.newFixedThreadPool(noOfThreads);

long startTime = System.nanoTime();
try {
    for (int i = 0; i<noOfThreads; i++) {
        service.submit(new Task());
    }
    service.shutdown();
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);     
} catch (InterruptedException e) {
    //Log exception here
} finally {
    long estimatedTime = System.nanoTime() - startTime;
}

推荐答案

问:您需要 while 吗?答:否

之前的 awaitTermination 调用只有在服务终止或(2 ^ 63-1)秒过去之后才会返回.(那是非常很长时间了.)

The previous awaitTermination call won't return until either the service has terminated, or (2^63 - 1) seconds have elapsed. (That is a very long time.)

更新-更新的版本对我来说还可以.

UPDATE - The updated version looks OK to me.

这篇关于等待所有线程完成其工作,然后测量经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆