aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads and Object Locks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads and Object Locks" Watch "Threads and Object Locks" New topic
Author

Threads and Object Locks

Jas Oberai
Ranch Hand

Joined: Jan 16, 2005
Posts: 231
Hi Friends,
I thought the o/p to be "XYZ" but its "ABC",the explanation says the synchronized run block won't execute until the synchronized main block completes and releases its lock,updating the array contents to "ABC".


but,I thought that if a thread holds a lock on any particular object,it can re-appy the lock on the same object insided the synchronized block.So,if the thread has locked the main method,can't it apply the lock on the run method simultaneously.Please explain me how this works out.Thanks.


SCJP 1.4 (88%)<br />SCWCD 1.4 (88%)
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18990
    
  40

but,I thought that if a thread holds a lock on any particular object,it can re-appy the lock on the same object insided the synchronized block.So,if the thread has locked the main method,can't it apply the lock on the run method simultaneously.Please explain me how this works out.Thanks.


By "re-appy", I am assuming you mean "re-acquire"?

Yes, if a thread already owns a lock, it can grab the lock as many times as it wants. No other thread may grab the lock until the thread releases all the acquires.

So yes, the main thread can call the run() method without any problems. However, it is not the main thread that will be calling the method.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
vinuharan haran
Ranch Hand

Joined: Feb 26, 2005
Posts: 64
Hi,
There are two threads.The main thread holds the lock.It starts another thread t1.The thread t1 will be waiting for the lock of sa which is held by main thread.When main thread releases the lock after setting the elements of the array,the thread t1 acquires the lock and it runs.So the output is ABC.
-vinu.
Jas Oberai
Ranch Hand

Joined: Jan 16, 2005
Posts: 231
Thanks Henry and Vinuharan,
For that concise and clear explanation.
Cheers!!!
 
jQuery in Action, 2nd edition
 
subject: Threads and Object Locks