To get 2000, synchronize on account before you setNumber(). Otherwise you've got a race condition. While both setNumber and getNumber are individually synchronized, the entire operation that you have inside the for loop is not synchronized.
And what the previous poster said.
Dal Singar Yadav
Joined: Jan 09, 2012
Dal Singar Yadav wrote:
Is the statement--
"Just before the main method exits, the account’s number field is guaranteed to have value 2000"
If Yes -- why ?
If No -- why No ?
Please explain in detail.
Thanks Sridhar for answer. But I want to ask how two threads can call getNumer() or SetNumer() method at the same time from run() method because each one is synchronized.
Q. Why this program prints 999999. According to me main has synchronized block on thread object. First of all how it is notified without any notify method and it may print any number from 1 to 999999 but result is always 999999.
Please clearly explain.
And Suggest Any book for Thread topic as I am preparing for SCJP 6.0 except Kathy sierra and Khalid Mughal.
When I read these books I think I have covered this topic but in some questions I can't predict possible answers.
As some of the posts already mention, please, QuoteYourSources ('scjp mock exam' is not enough - please tell us the details), UseCodeTags (otherwise, it becomes unnecessarily difficult to read the code) and ShowSomeEffort (where exactly you are stuck? what have you tried so far?)
Also, please limit one question per topic. You can ask further questions related to that particular code snippets in same topic, but for new code snippet, please create a new thread(topic).
Dal Singar Yadav wrote:Q. What are the possible outputs of this program and why ? Please explain clearly.
What possible outputs you've thought so far? Please note that this is a learning forum, and people here would be more than happy to help you learn. It is perfectly normal to get stuck during learning phase However, asking and providing ready-made answers is discouraged.
Dal Singar Yadav wrote:And Suggest Any book for Thread topic as I am preparing for SCJP 6.0 except Kathy sierra and Khalid Mughal.
Again, what exact part from Sierra-Bates and/or Mughal book is causing you trouble? I guess those two books are more than enough for every topic of OCPJP 6.