I am new to Java. Below is a code as an example of threads and synchronization.
public class A implements Runnable{
public synchronized void run(){
/*
some code here
*/
}
}
public class B {
public static void main(String[] args){
A obj1 = new A();
Thread t = new Thread(obj1);
A obj2 = obj1;
Thread t1 = new Thread(obj2);
t.start();
t1.start();
}
}
Now will this two threads block each other for same lock or will they get two different locks?
Thank you!!
(First, please stick to the Java coding conventions. A class name should always start with a capital letter. No exceptions.)
Only one of the threads will execute the
run()method at a time.The
A.run()method is an instance method, and it is declared assynchronized. These two facts mean that it will acquire a lock onthis(i.e. the instance ofA) before entering the method body, and release it on exiting. In short,run()locksthis.So in your main program you are creating a single
Ainstance and passing it as thetargetobject for two threads. They both need to execute therun()method on the same object, and this cannot happen at the same time … by the reasoning of the previous paragraph.This does not necessarily mean that one thread will block the other. It is also possible that the first thread to be started will have completed its
run()call before the second thread is ready to try the call. But we can say … definitively … that the two threads’ calls torun()will NOT overlap in time.