父类和子类中的同步方法是共用的同一个对象,从构造函数中打印this.toString()即可知而同步方法的所对象即为this,所以不仅是一个对象的同步方法会互斥,继承关系中的同步方法也会互斥
public class ConstructorTest {
public static void main(String[] args) {
final B b = new B();
new Thread(){
public void run() {
b.Atest();
};
}.start();
new Thread(){
public void run() {
b.Btest();
};
}.start();
}
}
打印类型
com.zhilong.bfsj.wenxi.B@60e128
com.zhilong.bfsj.wenxi.B@60e128
A begin seleep
A end seleep
B begin seleep
B end seleep
public class A {
private String AName = "";
public A(){
System.out.println(this.toString());
}
public synchronized void Atest(){
try {
System.out.println("A begin seleep ");
Thread.sleep(2000);
System.out.println("A end seleep ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class B extends A{
private String BName = "";
public B(){
System.out.println(this.toString());
}
public synchronized void Btest(){
try {
System.out.println("B begin seleep ");
Thread.sleep(2000);
System.out.println("B end seleep ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}