GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronization" Watch "synchronization" New topic
Author

synchronization

Vishwanath Krishnamurthi
Ranch Hand

Joined: Jun 04, 2007
Posts: 331
Hi folks,

In this code below, I have made the myMethod() synchronized, expecting that whichever thread executes it would not be interrupted by some other thread. But well, it is not happening so... What should I do in this to achieve synchronization?



OUTPUT:
Thread A: 0
Thread A: 1
Thread A: 2
Thread A: 3
Thread A: 4
Thread A: 5
Thread A: 6
Thread B: 0
Thread B: 1
Thread B: 2
Thread B: 3
Thread B: 4
Thread B: 5
Thread B: 6
Thread B: 7
Thread A: 7
Thread A: 8
Thread A: 9
============
Thread B: 8
Thread B: 9
============

I am stuck for about four-five hours now with not being able understand locks...


Blog
Luca Romanello
Greenhorn

Joined: May 30, 2002
Posts: 11
Hi
I think the point is you're not obtaining what you want because you are not synchronizing the same object, but two different ones. That means that thread a's myMethod will be locked for every object accessing it (that is, just a itself), and the same goes for b's myMethod. Two different instances = two different locks.
Try with this (a little strange, I know):

That means, two different threads accessing the same Runnable instance.
Hope this helps
Regards
LR
[ December 10, 2007: Message edited by: Luca Romanello ]
Vishwanath Krishnamurthi
Ranch Hand

Joined: Jun 04, 2007
Posts: 331
Thanks a lot, Luca. And finally, I am understanding this... Thanks again...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization