aspose file tools*
The moose likes Java in General and the fly likes Threads and synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Threads and synchronization " Watch "Threads and synchronization " New topic
Author

Threads and synchronization

Sid Shankar
Greenhorn

Joined: Oct 10, 2012
Posts: 5
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

Joined: Dec 08, 2010
Posts: 1509
    
    5

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.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Sid Shankar
Greenhorn

Joined: Oct 10, 2012
Posts: 5
Thanks Anayonkar, yes that makes sense.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads and synchronization