在下面的例子中,對實例變量僱員(未在此)中獲得鎖,但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();
}
}
我不明白。你寫他們鎖定在變量,這是預期的行爲。那怎麼了? –