完整执行时间多线程 java



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

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

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

你最好使用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它们也会被执行。

使用 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);
   } 

相关内容

  • 没有找到相关文章

最新更新