The questions:
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);
}
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.
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.