我有一个命令行应用程序。它运行循环说100次,并在循环中使用线程调度任务。我正在使用ExecutorService,因此任何时候都有4个线程在运行。
循环结束后,我想打印摘要消息。例如。完成所有100项任务所需的时间。当我逐步完成代码时,调试器直接进入摘要部分,但其他任务仍在运行。我理解这是因为每个线程都是自己运行的。那么如何在所有线程完成后才打印消息?
ExecutorService exec = Executors.newFixedThreadPool(4);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Runnable requestHandler = new Runnable() {
@Override
public void run() {
try {
// call task function in here
} catch (Exception ex) {
}
}
};
exec.execute(requestHandler);
}
exec.shutdown();
long endTime = System.currentTimeMillis();
LOGGER.info("******************SUMMARY******************");
LOGGER.info("Time taken : " + ((endTime - startTime)/1000) + " seconds, "
+ ((endTime - startTime)/1000/60) + " minutes");
答案 0 :(得分:5)
从主线程中,您可以创建另一个线程来执行从声明exec
到exec.shutdown();
的所有操作。创建此线程后,将主线程放到wait
。在新主题的操作结束时(在exec.shutdown();
之后),您应该notify
它。
答案 1 :(得分:3)
请参阅为简洁而复制的http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html示例
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
答案 2 :(得分:1)
基本上你需要等到ExecutorService isTerminated()
方法返回true。您可以使用awaitTermination()
作为目的。
答案 3 :(得分:0)
The solution for you based on your code:
ExecutorService exec = Executors.newFixedThreadPool(4);
long start = System.currentTimeMillis();
//Your code
exec.shutdown();
while(true) {
if(exec.isTerminated()) {
long end = System.currentTimeMillis();
System.out.println("Time : " + (end - start));
break;
}
Check this out! It works!