我在我的Multithreaded code
之一中使用Executor service
。我试图看看我的所有线程是否都完成了他们的工作,然后我需要完成某些任务。等待所有线程完成他们的工作,然后测量已用时间
目前我需要测量已过去的时间,所以我只能测量所有线程完成执行任务后所经过的时间。所以我现在有这个代码?我在finally block
中测量time elapsed
。
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 loop
在不在?我目前的做法是对的吗?
更新的代码: -
所以下面的代码应该工作正常。对?
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;
}
谢谢Stephen的建议。那意味着我不会需要while循环吗?然后我可以测量finally块中的时间呢? – AKIWEB 2013-02-12 03:33:31
你真的不需要最终。如果某个其他线程中断了当前的线程,你只会得到一个'InterruptedException'。在那种情况下,我几乎认为你不在乎时间是什么......'因为这不会是一个有意义的衡量标准。 – 2013-02-12 09:51:28