全执行时间多线程Java

时间:2019-04-26 07:00:34

标签: java multithreading execution nanotime

我想测量完整的执行时间(所有线程完成时)。 但是我的代码在这里行不通,因为当主方法结束时,其他线程仍在运行,因为它们比主方法花费的时间更长。

class Hello extends Thread {
   @Override
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("Hello");
         try {
            Thread.sleep(500);
         } catch (final Exception e) {
         }
      }
   }

}

class Hi extends Thread {
   @Override
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("Hi");
         try {
            Thread.sleep(500);
         } catch (final Exception e) {
         }
      }
   }
}

public class MultiThread {
   public static void main(String[] args) {
      final long startTime = System.nanoTime();
      final Hello hello = new Hello();
      final Hi hi = new Hi();
      hello.start();
      hi.start();

      final long time = System.nanoTime() - startTime;
      System.out.println("time to execute whole code: " + time);

   }

}

我正在尝试使用System.nanoTime()来测量在单线程v / s多线程上运行程序时的执行时间。

2 个答案:

答案 0 :(得分:6)

只需在hello.join()之后添加hi.join()hi.start()

您最好使用ExecutorService

public static void main(String[] args) {
    final long startTime = System.nanoTime();
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new Hello());
    executor.execute(new Hi());
    // finish all existing threads in the queue
    executor.shutdown();
    // Wait until all threads are finish
    executor.awaitTermination();
    final long time = System.nanoTime() - startTime;
    System.out.println("time to execute whole code: " + time);
}

ExecutorService通常在执行RunnableCallable,但是由于Thread在扩展Runnable,它们也被执行。

答案 1 :(得分:4)

使用join()将停止代码进入下一行,直到线程死亡为止。

 public static void main(String[] args) {
      final Hello hello = new Hello();
      final Hi hi = new Hi();

      final long startTime = System.nanoTime();

      hello.start();
      hi.start();

      try{
          hello.join();
          hi.join();
      }
      catch(InterruptedException e){}
      final long time = System.nanoTime() - startTime;
      System.out.println("time to execute whole code: " + time);

   }