• Post Reply Bookmark Topic Watch Topic
  • New Topic

why does synchronized not work here?  RSS feed

 
Karen Nelson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm just starting with threads, using Head First Java. I tried to code the Ryan and Monica example (Ryan and Monica both withdraw $10 at a time from their joint bank account...) and everything went swimmingly until I tried to put in a synchronized block to avoid overdrafts. If this works correctly, the total amount withdrawn should always be $100 (which is also true if I put the Thread.sleep() in a more reasonable location, but I'm doing this to figure out how threads work). However, in the code below, $110 gets withdrawn about 20% of the time on my machine.

What am I doing wrong?

Thank you!! Karen.

 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your two threads are synchronising on different objects, so the synchronisation has no effect. For it to work, they need to synchronise on the same object. Perhaps the outer class could create an object on which both inner classes can synchronise.
 
Karen Nelson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, thank you! that's totally clear but I never would have figured it out... I made an Account object and synchronized on that and everything's fine.

-K
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!