• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads and synchronization

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

In the following code, after a few tries, I got an output such as this?

sandy starting
jason starting
jason ending
sandy ending

I have synchronized the run method so that the first entering thread will have the lock and finish first. But seems like "sandy" entered first and yet, "jason" is the one who finishes first followed by "sandy". Why is this so? Thanks for the help.


 
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sid,

Welcome to CodeRanch!

What you are trying to do is - acquire a lock on the object while invoking run method.


is same as

However, you are creating two different objects of MyThread class. Each object is eligible to get a lock 'on itself' - that is, the lock acquired by mt1 will be different than that of mt2, and hence both thread won't block each other.

I hope this helps.
 
Sid Shankar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Anayonkar, yes that makes sense.

 
reply
    Bookmark Topic Watch Topic
  • New Topic