0

I want to count the time, how long all my task will work. But my variable timeElapsed is always 1. Why? Here is my code:

public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for(String arg : args){
            new Thread(() -> {
              /* ... */
        }).start();
        }
        long finish = System.currentTimeMillis();
        long timeElapsed = finish - start; //always is 1
        System.out.println("Elapsed time: " + timeElapsed); 

    }
}
Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
Kamikaze
  • 23
  • 1
  • 4
  • 5
    You are not waiting for the threads to finish. You just start them, which means they are running in parallel doing their job. You can use `join()` to wait that they finish. – Progman Oct 08 '20 at 21:23
  • The threads might also have sub-millisecond runtimes, Use `System.nanoTime()` – Big Guy Oct 08 '20 at 21:31

0 Answers0