完全执行时间多线程java [重复]

问题描述 投票:2回答:2

这个问题在这里已有答案:

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

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()来测量时间的执行时间。

java multithreading execution nanotime
2个回答
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,他们也被执行。


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

   } 
© www.soinside.com 2019 - 2024. All rights reserved.