首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >完全执行时间多线程java

完全执行时间多线程java
EN

Stack Overflow用户
提问于 2019-04-26 15:00:34
回答 2查看 444关注 0票数 2

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

代码语言:javascript
复制
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()来测量一个程序在单线程和多线程上运行时的执行时间。

EN

回答 2

Stack Overflow用户

发布于 2019-04-26 15:06:15

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

你最好使用ExecutorService

代码语言:javascript
复制
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,所以它们也会被执行。

票数 5
EN

Stack Overflow用户

发布于 2019-04-26 15:12:28

使用join()将阻止代码转到下一行,直到线程死掉。

代码语言:javascript
复制
 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);

   } 
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55862371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档