gpt4 book ai didi

java - 等待所有线程完成其工作,然后测量耗时

转载 作者:行者123 更新时间:2023-11-30 04:30:10 24 4
gpt4 key购买 nike

我正在我的一个多线程代码中使用执行器服务。我试图查看我的所有线程是否都完成了工作,然后我需要执行某些任务。

目前我需要测量耗时,所以我只能在所有线程完成执行该作业后才能测量耗时。那么我现在有这个代码吗?我正在测量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循环?我现在的做法对不对?

更新的代码:-

所以下面的代码应该可以正常工作。对吗?

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吗?答:没有。

在服务终止或经过 (2^63 - 1) 秒之前,之前的 awaitTermination 调用不会返回。 (这是一个非常很长的时间。)

<小时/>

更新 - 更新后的版本对我来说看起来不错。

关于java - 等待所有线程完成其工作,然后测量耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14824806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com