全执行时间多线程Java

Eck*_*erd 2 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);

   }

}
Run Code Online (Sandbox Code Playgroud)

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

Sir*_*Lot 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);
}
Run Code Online (Sandbox Code Playgroud)

一个ExecutorService正在正常执行RunnableCallable,但由于Thread被延伸Runnable他们太执行。