Search code examples
javajava-threads

How to measure how long a thread will exactly take from new to end in java


The questions:

  1. is there anyway to get the exact time a thread will take from new to end?
  2. why do the results in each time have huge differences (see code below)?

The code:

public void process2(){
    final long start = System.currentTimeMillis();
    Thread newT = new Thread(new Runnable() {
        @Override
        public void run() {
            // long end = System.currentTimeMillis();
            // System.out.println((end-start));

            for (int i = 1, sum = 0; i < 1000; i++) {
                sum += i;
            }
        }
    });
    long end1 = System.currentTimeMillis();
    System.out.println("new thread time took :" + (end1 - start));
    newT.start();

    int i = 0;
    while (newT.isAlive()) {
        i++;
    }

    long end = System.currentTimeMillis();
    System.out.println("total time:" + (end - start));
    System.out.println("judge count:" + i);

}

Solution

    1. It is usually more relevant to measure the the time of execution, that is the time taken to execute run() method. This time will generally be similar between different runs.

    2. The creation on a new Thread object is rather costly, and depends on currently available resources of the system, which is why there can be big differences in time taken between Thread creation and its execution. What's more, is that before destruction of a thread, there is a clean-up process that can also take up a significant amount of time.

    One ways to optimize the thread management time (creations/destruction) is to use a ThreadPool or an ExecutorService. See Oracle concurrency tutorial for more details.