I was reading about thread pools and found that thread creation is considered an expensive process. This counteracted my intuition and I decided to put it to test:
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
}
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
This prints 696ms
on my system. So the time to create one thread is close to 0.69 millisecond. Why is this considered slow?
Edit:
public class Test {
static int a = 1;
static long start;
static void setA() {
++a;
if(a>=1000) {
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
}
public static void main(String[] args) {
start = System.currentTimeMillis();
for (int i = 0; i <= 1000; ++i) {
new Thread(new Runnable() {
@Override
public void run() {
setA();
}
}).start();
}
}
}
This prints 729ms
.