2015-01-12 5 views
0

시간 계산이 주 스레드에 있고 durationTime 값을 계산하고 threadPool을 실행하기 때문에 아래 코드를 실행 한 후 시간이 0으로 표시됩니다.멀티 스레드 응용 프로그램의 실행 시간은 어떻게 찾을 수 있습니까?

스레드를 실행하는 동안 걸린 총 시간을 찾고 싶습니다.

public static void main(String[] args) { 
     long startTime = System.nanoTime(); 
     int numberThread=10; 
     String apiToBeCall="abcApi"; 

     Runnable r1=new SFSrmMainClass(apiToBeCall); 

     ExecutorService threadPool=Executors.newFixedThreadPool(numberThread); 
     for (int i=0;i<numberThread;i++) 
     { 

      threadPool.execute(r1); 
     } 
     threadPool.shutdown(); 

     long endTime = System.nanoTime(); 
     long durationTime = (endTime - startTime); 
     System.out.println("time for "+apiToBeCall +" is having thread="+numberThread +" is "+durationTime/1000000000); 
    } 

답변

0

awaitTermination은 모든 스레드가 완료 될 때까지 주 스레드를 차단하는 shutdown()을 호출 한 후 사용하십시오.

예 :

나는 "시간"매개 변수를 줄 필요가 awaitTermination를 사용
static long measureTasks(final int nThreads, final Runnable... tasks) 
    throws InterruptedException 
{ 
    final ExecutorService pool = Executors.newFixedThreadPool(nThreads); 
    final long startTime = System.nanoTime(); 

    for (Runnable task : tasks) 
     pool.execute(task); 

    pool.shutdown(); 
    pool.awaitTermination(10, TimeUnit.SECONDS); 

    return System.nanoTime() - startTime; 
} 
+0

, 스레드의 실행이 "@NiteshBagri 그것을 10 초 등의 시간을 줄 것이다, 십초 이상했다 또는 이상 십초 –

+0

을 반환하는 경우 등 종료 요구 이후에 모든 태스크가 실행을 완료하거나, 타임 아웃이 발생하는지, 현재의 thread가 중단 될지, 어느 쪽이든 먼저 발생하는 것을 블록 할 때까지 블록합니다.이 executor가 종료하면 true, 종료 전에 타임 아웃이 경과하면 false가됩니다. 스레드가 완료되기 전에 awaitTermination은 false를 반환합니다. –

관련 문제