class JoinDemo extends Thread {
JoinDemo(String nm) {
setName(nm);
start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
System.out.println(getName() + " exiting.");
}
public static void main(String args[]) {
JoinDemo t1 = new JoinDemo("One");
JoinDemo t2 = new JoinDemo("Two");
JoinDemo t3 = new JoinDemo("Three");
try {
t1.join();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Main Thread Exits now.");
}
}
The output obtained is:
1
1
1
2
2
2
3
3
3
4
4
4
5
5
Three exiting.
One exiting.
5
Main Thread Exiting
Two exiting.
I wrote the above program after going through various sites to understand the concept of Join(). But still i'm unable to get it.The problem I'm facing is that I have used t1.join(). So thread one should exit before three, but here thread three exits before one. And every time I run the program the output is different. As sometimes it is two exiting before one, or three before one. Shouldn't thread one exit before any other thread?? As t1.join() waits for thread one to terminate before three and one??