• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization

 
Vishwanath Krishnamurthi
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Luca Romanello
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Luca. And finally, I am understanding this... Thanks again...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic