【问题标题】:Measuring execution time over multiple threads测量多个线程的执行时间
【发布时间】:2016-06-11 14:26:19
【问题描述】:

我想测量完整的执行时间(所以当所有线程都完成时)。 System.currentimeMillis 的技巧在这里不起作用,因为当主方法结束时,我自己创建的线程仍然会运行,因为它们需要比主方法更长的时间来处理。 我该怎么做?

我举个例子。

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.
}
}

【问题讨论】:

    标签: java multithreading time measure


    【解决方案1】:

    您可以使用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);
    

    【讨论】:

      【解决方案2】:

      在测量结束时间之前,您应该考虑使用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

      【讨论】:

      • 如果这有帮助,请告诉我。
      猜你喜欢
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 2011-02-16
      • 2017-05-31
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多