• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confused in Thread join() code  RSS feed

 
Sandeep Mukherji
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have copied a code from Khalid A. Mughal on join(), and a bit confused about how the output came. the code is as followed


The output is comming like :

main
23
24
13
21
Thread-0 will join after the completion of other threads
14
22
11
Thread-1 will join after the completion of other threads
12
My concern is, how this output is arrived. Can anyone explain please.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Firstly, the output that you have got may vary from one run to another.
The only thing you are insuring using join is that the line:



is executed after the thread passed in createThread() has finished running.
However, the value of "i" when the above is executed still depends on how many System.out. statements have been executed by then i.e. how many times "i" has been incremented.

I modified the program a little as follows:



and got the following output:



This will give you a better understanding.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!