Полное время выполнения, многопоточность, 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);

   }

}

Я пытаюсь найти время выполнения, когда программа выполняется в одном потоке против многопоточности, используя System.nanoTime() для измерения времени.


person Eckerd    schedule 26.04.2019    source источник


Ответы (2)


Просто добавьте 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 обычно выполняет Runnable или Callable, но поскольку Thread расширяет Runnable, они тоже выполняются.

person SirFartALot    schedule 26.04.2019

Использование 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);

   } 
person Doc    schedule 26.04.2019