I just have started learning threads and come upon misunderstanding of how they work.
Here is my class:
public class MyThread extends Thread {
private static int NUM = 0;
private int id;
public MyThread() {
id = NUM++;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new MyThread().start();
}
}
public void run() {
System.out.println(id + " started");
try {
Process p = Runtime.getRuntime().exec("javac -version");
p.waitFor();
} catch (Exception e) {
System.out.println("Call a doc!");
}
System.out.println(id + " finished");
}
}
/*
Just a sidenote.
I am creating new javac process just to slow an application down.
Simple System.out.println(…) is a way faster.
*/
Why do I always get all "… started" messages at first and after that "… finished" messages? No matter how many threads have I started, I always see:
0 started
1 started
2 started
3 started
4 started
5 started
6 started
7 started
8 started
9 started
0 finished
1 finished
3 finished
4 finished
8 finished
5 finished
2 finished
6 finished
9 finished
7 finished
Isn't the purpose of threads to parallelize execution?
Maybe I need to synchronize something? Or made careless mistake? Or…?
Explain, please.
UPDATE:
Why don't I see, let's say:
0 started
1 started
0 finished
2 started
1 finished
2 finished
Thank you all for treatment.