2016-02-28 128 views
1

我想測量完整的執行時間(所以當所有線程完成時)。 System.currentimeMillis的技巧在這裏不起作用,因爲當main方法結束時,我自己創建的線程仍然會運行,因爲它們比main方法處理需要更長的時間。 我該怎麼做?測量多線程的執行時間

我舉個例子。

public class Main { 

public static void main(String[] args) { 

    long start = System.currentTimeMillis(); 

    new Thread(() -> { 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    }).start(); 

    long end = System.currentTimeMillis(); 

    System.out.println(end - start); // Won't work because my new Thread will still be running here. 
} 
} 

回答

2

您可以使用ExecutorService

long startTime = System.nanoTime(); 
ExecutorService executorService = Executors.myPool(); 
for(conditions) 
    executorService.submit(new myThread()); 

然後不要忘記shutdown()

發起在以前已提交任務的執行一個有序的關閉,但沒有新的任務將被接受。如果已關閉,調用沒有其他影響。

executorService.shutdown(); 

而且wait

關機請求後

阻塞,直到所有任務完成執行,或發生超時,或者當前線程中斷,無論哪一個首先發生。

executorService.awaitTermination(1, TimeUnit.HOUR); // however long you need 

然後計算:

long totalTime = System.nanoTime() - startTime; 

System.out.printf("The total time everything took was %.3f ms %n", totalTime/1e6); 
0

你應該考慮測量結束時間之前使用thread Joins。這將確保主線程僅在所有其他線程退出時退出。

package threadsync; 

public class MeasureRunningTime { 

public static void main(String[] args) { 

    long start = System.currentTimeMillis(); 

    Thread th = new Thread(){ 
     public void run() { 
      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     }; 
    }; 

    th.start(); 

    try { 
     th.join(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

    long end = System.currentTimeMillis(); 

    System.out.println("The thread took:" + (end - start) + "ms"); 
} 

}

輸出在這種情況下應該是:

線程了:5003ms

+0

讓我知道,如果這有助於。 – Learner