Reputation: 1481
I have the following code
class Multi extends Thread{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(i + ": "+Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi t1=new Multi();
t1.setName("First Thread");
Multi t2=new Multi();
t2.setName("Second Thread");
Multi t3=new Multi();
t3.setName("Third Thread");
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){System.out.println(e);}
t3.start();
}
}
**
The output varies every time I run :
1st time Output
1: Second Thread
2: Second Thread
3: Second Thread
1: First Thread
2: First Thread
3: First Thread
1: Third Thread
2: Third Thread
3: Third Thread
=============================================
2nd time Output
1: First Thread
2: First Thread
3: First Thread
1: Second Thread
2: Second Thread
3: Second Thread
1: Third Thread
2: Third Thread
3: Third Thread
*************************************************
Since t2.join()
is called after t1.join()
how come 1st output is coming ? Shouldn't t2
wait for t1
to execute?
Please help me understand the join()
method behavior, if possible with more code snippet examples
Upvotes: 2
Views: 129
Reputation: 7804
For Thread t2
to wait for t1
to finish off.. you need to write t1.join()
in the run()
method for t2
.
In your case, main thread will wait for t1 and t2 to finish off and it will then start thread t3
. This is evident from the output which clearly shows that t3 had started after t1 and t2 got completed.
Upvotes: 2
Reputation: 1324
The output will vary because it can be predicted how t1
and t2
threads will work behind the scene. That's how threads work on JVM by default. It has nothing to do with your join()
methods. In your case when you call t1.join()
it only means that the "main" thread will wait until t1
thread will finish its job. The same is about t2.join()
Upvotes: 1
Reputation: 178263
The join
method doesn't affect the order of execution of any currently executing Thread
s. All it does it make the current thread wait until the Thread
specified ends.
Upvotes: 2
Reputation: 691715
t.join()
blocks the current thread (the main thread in your example) until the thread t
has finished executing. It doesn't block any other thread, and doesn't prevent any other thread to run.
Your example starts t1 and t2. So t1 and t2 run in parallel. And the main thread blocks until t1 is completed. Once t1 is completed, it blocks until t2 is completed. t2 might very well has finished executing before t1. In this case, t2.join()
will return immediately.
Upvotes: 7