2

I want to measure the full execution time (when ALL threads are done). But my code won't work here, because when the main-method ends while the other threads will still be running because they take longer time to process than the 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);

   }

}

I am trying to find get the execution time when a program is run on a single thread v/s multithread using of System.nanoTime() to measure time.

Marvin Klar
  • 1,869
  • 3
  • 14
  • 32
Eckerd
  • 21
  • 3

2 Answers2

5

Just add hello.join() and hi.join() after hi.start()

You'd better use an 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);
}

An ExecutorService is normally executing Runnable or Callable, but since Thread is extending Runnable they are executed too.

SirFartALot
  • 1,215
  • 5
  • 25
4

Using join() will stop the code from going to the next line until the thread is dead.

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

   } 
Doc
  • 10,831
  • 3
  • 39
  • 63