I wrote a program in Java to print 10 hundred thousand in a for
loop.
for (int i =0;i<1000000;i++){
System.out.println(i);
}
It took around 7.5 seconds
.
I wrote a custom class in Java that implements Runnable
interface, it takes 2 parameters as a limit to print the values between 2 values.
public class ThreadCustom implements Runnable {
int start;
int end;
String name;
ThreadCustom(int start, int end, String name){
this.start = start;
this.end = end;
this.name = name;
}
@Override
public void run() {
for(int i =start; i<=end;i++){
System.out.println(i);
}
}
}
I created 10 objects of my custom thread class, assigned each object a chunk of 100k numbers to print so at the end I get all the 10 hundred thousands
printed (not in order definitely) but it takes around 9.5 seconds.
What's the reason for this 2 seconds delay
? Is that because of time slicing and context switching that takes place between threads? I am executing a java process and it spawns 10 threads. Am I thinking in the right direction?
Updated: commented System.out.println
to see how it performs when there is an iteration.
Printed time without threads
2019-04-14 22:18:07.111 // start
2019-04-14 22:18:07.116 // end
Using ThreadCustom class:
2019-04-14 22:26:42.339
2019-04-14 22:26:42.341