Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full execution time multi thread java [duplicate]

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.

like image 552
Eckerd Avatar asked May 31 '26 13:05

Eckerd


1 Answers

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.

like image 103
SirFartALot Avatar answered Jun 02 '26 02:06

SirFartALot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!