Originally posted by John Edwin:
public class Joining {
static Thread createThread(final int i, final Thread t1) {
Thread t2 = new Thread() {
public void run() {
System.out.println(i+1);
try {
t1.join();
} catch (InterruptedException e) {
}
System.out.println(i+2);
}
};
System.out.println(i+3);
t2.start();
System.out.println(i+4);
return t2;
}
public static void main(String[] args) {
createThread(10, createThread(20, Thread.currentThread()));
}
}
You see, the currentThread (main
thread) is being passed to the createThread method.
Inside createThred method a new thread t2 is created.
The run method of t2 is implemented such as it waits for thread t1 to finish, because of t1.join statement.
The t1 actually is main thread.
T2 will finish last, always.
The last print statement in T2 is 12.
Hope it helps.