• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding locks.....pls help me out  RSS feed

 
nishant vats
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Am confused abt locks...can u explain what is concept of lock...in following code i have two thread objects _th1,_th2 can anyone explain who will acquire the lock becoz they themselves are thread object...i am nt still able to get that "thread will acquire the lock on object.." here what is thread and object ? pls clearly distnguish between thread and object..

class ThreadExample extends Thread{
public void run(){
System.out.println("Execting run");
}
}
public class ThreadSim {
public static void main(String args[]){
ThreadExample _th1 = new ThreadExample();
_th1.start();
ThreadExample _th2 = new ThreadExample();
_th2.start();
}

}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every object has a lock - tho lock is not exactly the right word but the right one isn't coming to me just now. The lock can have no object holding it or one object holding it. When thread T1 holds the lock and thread T2 asks for it, T2 will wait until T1 gives up the lock.

When you make a method synchronized, thread T1 gets the lock for the object that has the method. So if T2 tries to run that method or any other synchronized method it will have to wait until T1 returns from the synchronized method.

When you synchronize on some object, thread T1 gets the lock for that object. This doesn't have to be the one the method is running on. A number of object instances might share a common lock.


Does that help? This is hard to do without pictures!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!