java - 多线程java的完整执行时间

标签 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()测量时间。

最佳答案

只需在 hi.start() 之后添加 hello.join()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 它们也会被执行。

关于java - 多线程java的完整执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862371/

相关文章:

c - OpenMP:重写 for 循环以便可以并行化?

python - 在 Macbook 关闭的情况下保持 Jupyter notebook 运行

java - 尝试打印出 "best customer"谁花费的金额最多

java - 如何在不覆盖 Sets 的情况下将多个 Maps <Character, Set<String>> 组合在一起

java - Hibernate Validator boolean 逻辑

java - 通过对象序列化流发送具有不同字段的相同对象

java - 不仅为我的帐户获取 Facebook 生日

python - 使用线程读取文件并传递数据

java - 尝试将 flyway 用于多个数据库实例

C++ 以编程方式查找可执行根目录的可移植方式