首页 > 解决方案 > 完整执行时间多线程java

问题描述

我想测量完整的执行时间(当所有线程都完成时)。但是我的代码在这里不起作用,因为当主方法结束而其他线程仍将运行时,因为它们比主方法需要更长的时间来处理。

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);

   }

}

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

标签: javamultithreadingexecutionnanotime

解决方案


只需添加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);
}

AnExecutorService通常正在执行Runnableor Callable,但由于Thread正在扩展Runnable它们也被执行。


推荐阅读