In the below example, lock is obtained on instance variable employee (not on this), but still Threads of TestClass1 are getting locked while entering synchronized block. Any advice why is this behaviour. As far as my understanding it should get locked if its synchronization is on this.
public class TestClass{
public static void main(String args[]){
TestClass1 obj = new TestClass1();
Thread t1 = new Thread(obj, "T1");
Thread t2 = new Thread(obj, "T2");
t1.start();
t2.start();
}
}
class TestClass1 implements Runnable{
Employee employee = new Employee();
public void myMethod () {
synchronized (employee) {
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void myOtherMethod() {
synchronized (employee) {
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
myMethod();
myOtherMethod();
}
}