在下面的示例中,在实例变量employee 上获得了锁(不是在this 上),但TestClass1 的线程在进入同步块时仍然被锁定。任何建议为什么是这种行为。据我了解,如果它的同步在此,它应该被锁定。
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();
}
}