Wednesday, 7 August 2013

Thread join() method output confusion

Thread join() method output confusion

I was researching on Thread join() method and i came across the
ThreadJoinMethod post on stackoverflow. I modified the code to develop a
working example and i am confused on the output. Code snippet is.
/**
* Created with IntelliJ IDEA.
* User: Ben
* Date: 8/7/13
* Time: 5:35 PM
* To change this template use File | Settings | File Templates.
*/
class JoinRunnable implements Runnable{
public void run() {
for(int i =0 ; i < 4 ; i++){
System.out.println(i);
}
}
}
public class TestJoin{
public static void main(String[] args) throws InterruptedException {
JoinRunnable joinRunnable = new JoinRunnable();
Thread t1 = new Thread(joinRunnable);
Thread t2 = new Thread(joinRunnable);
t1.start();
t2.start();
System.out.println("Currently running thread: " +
Thread.currentThread().getName());
t1.join();
t2.join();
System.out.println("I must wait");
}
}
The output of the following program is :-
0
1
2
3
0
1
2
3
Currently running thread: main
I must wait
I am confused at the output. The current thread will be joined after the
call to join on t1 and t2 but why the statement, "Currently Running
Thread: main" is printing after t1 and t2 completes? Am i missing some
important concept here? Because main() will join t1 and t2 after the join
statements not before. Can someone elaborate on it?

No comments:

Post a Comment