2013-02-12 54 views
1

我在我的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; 
} 

回答

1

问:你需要while?答:不可以。

之前的awaitTermination呼叫将不会返回,直到服务终止或(2^63 - 1)秒过去。 (这是一个非常长的时间。)


UPDATE - 更新后的版本看起来OK我。

+0

谢谢Stephen的建议。那意味着我不会需要while循环吗?然后我可以测量finally块中的时间呢? – AKIWEB 2013-02-12 03:33:31

+1

你真的不需要最终。如果某个其他线程中断了当前的线程,你只会得到一个'InterruptedException'。在那种情况下,我几乎认为你不在乎时间是什么......'因为这不会是一个有意义的衡量标准。 – 2013-02-12 09:51:28

相关问题