File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Threads and synchronization " Watch "Threads and synchronization " New topic

Threads and synchronization

Sid Shankar

Joined: Oct 10, 2012
Posts: 5

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

Joined: Dec 08, 2010
Posts: 1545

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.

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

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

I agree. Here's the link:
subject: Threads and synchronization
It's not a secret anymore!