我Executor service
在我的一个中使用Multithreaded code
。我正在尝试查看我的所有线程是否都完成了他们的工作,然后我需要执行某些任务。
目前我需要测量经过的时间,所以我只能在所有线程完成执行那里的作业后才能测量经过的时间。所以我目前有这个代码?我正在测量time elapsed
。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 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;
}