I have this java main method as
public class ThreadJoinExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestJoinClass t1 = new TestJoinClass("t1");
TestJoinClass t2 = new TestJoinClass("t2");
TestJoinClass t3 = new TestJoinClass("t3");
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
//thread 3 won't start until thread 2 is complete
t3.start();
}
}
My thread class is
public class TestJoinClass extends Thread{
//Constructor to assign a user defined name to the thread
public TestJoinClass(String name)
{
super(name);
}
public void run(){
for(int i=1;i<=5;i++){
try{
//stop the thread for 1/2 second
Thread.sleep(500);
}
catch(Exception e){System.out.println(e);}
System.out.println(Thread.currentThread().getName()+
" i = "+i);
}
}
}
The output for this program is
t1 i = 1
t1 i = 2
t1 i = 3
t1 i = 4
t1 i = 5
t3 i = 1
t2 i = 1
t3 i = 2
t2 i = 2
t3 i = 3
t2 i = 3
t3 i = 4
t2 i = 4
t3 i = 5
t2 i = 5
I have just a minor question. I was wondering why does t3 start running first instead of t2? In the code, it shows that t2.start() executes first before t3.start(). Shouldn't the output show that t2 executes first before t3 as well? Thank you