• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

k&b SCJP 6 Chapter 9: Threads self test q15

 
Ranch Hand
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Following code is from K&B p769:



although I've slightly modified lines 9 & 11 to include the thread name in the output.

According to K&B's answer:

With either fragment, the first output must be yo.



I don't see why this must be so. I think that if the unsynchronized chat() is used, as above, then thread t1 could get to line 6 first & set the flag to its own id. Then, thread t2 could get some processor time and start executing chat(). The flag != 0 by now, so t2 leaves the flag unchanged and since the flag doesn't equal its own id, [dude] gets printed first.

In fact, running the program, occasionally [dude] does get printed first.

Maybe I should post to the 'Compiling errata for K&B, SCJP 6' thread, it's not currently mentioned there.
 
Sheriff
Posts: 9697
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Richard, if you've not made any error in copying the code, then I agree the first output can be "dude" with fragment 2...
 
Richard Hayward
Ranch Hand
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ankit. I'd wondered if I'd misunderstood the question somehow.
I've added a post to the scjp 6 errata thread.
 
Please enjoy this holographic presentation of our apocalyptic dilemma right after this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic