I am new to Java and the concept of multi-threading. Here's my experimental code:
public class Multithread implements Runnable {
Thread t;
public Multithread(int prior, String name) {
this.t = new Thread(this, name);
this.t.setPriority(prior);
this.t.start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
if (this.t.getName().equals("thread1")) {
System.out.println("First Child Thread Loop No " + i);
}
else {
System.out.println("Second Child Thread Loop No " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
new Multithread(10, "thread1");
new Multithread(7, "thread2");
}
}
The output is:
First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
Second Child Thread Loop No 3
First Child Thread Loop No 3
Second Child Thread Loop No 4
First Child Thread Loop No 4
Second Child Thread Loop No 5
First Child Thread Loop No 5
Well I expected to be a simple as this:
First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
First Child Thread Loop No 3
Second Child Thread Loop No 3
First Child Thread Loop No 4
Second Child Thread Loop No 4
First Child Thread Loop No 5
Second Child Thread Loop No 5
I expect first thread to get executed always before the second thread. Please explain my output. Thanks in advance.