• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and Object Locks

 
Jas Oberai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 21016
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
vinuharan haran
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry and Vinuharan,
For that concise and clear explanation.
Cheers!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic