This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes nikos thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "nikos thread question" Watch "nikos thread question" New topic

nikos thread question

Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521

why is the answer not guarenteed to be 2000? arent setNumber and getNumber this becasue both the threads have entered the run method and started the loop...and once the first thread finishes with setNumber and getNumber the other one can start it enter too...........?

scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later" someone unknown
Martin Sergeant

Joined: May 20, 2003
Posts: 24
The problem is that although the setNumber and getNumber methods are synchronized,
the action of getting and setting the number is not atomic. Therfore it is possible
for a thead call getNumber and before it has time to call setnumber , another thread
may nip in and call getNumber, thus both threads will call setnumber using the same
number. This can be avoided by combining setNumber and getNumber in one
synchronized method

I agree. Here's the link:
subject: nikos thread question
jQuery in Action, 3rd edition