Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Confused in Thread join() code

 
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.
 
Bartender
Posts: 1638
IntelliJ IDE MySQL Database Java
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic