在下面的例子中,对实例变量雇员(未在此)中获得锁,但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();
}
}
我不明白。你写他们锁定在变量,这是预期的行为。那怎么了? –