Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and synchronization

 
Sid Shankar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • 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.


 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Anayonkar, yes that makes sense.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic