Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to undersatand join() method

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

like image 979
Pradeep K M Avatar asked Dec 02 '25 11:12

Pradeep K M


2 Answers

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.

like image 100
JB Nizet Avatar answered Dec 04 '25 00:12

JB Nizet


The join method doesn't affect the order of execution of any currently executing Threads. All it does it make the current thread wait until the Thread specified ends.

like image 20
rgettman Avatar answered Dec 04 '25 00:12

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!