/**
父类
*/
public class SynchronizedDemo1 implements Runnable {
@Override
public void run() {
try {
method();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void method() throws InterruptedException {
synchronized(SynchronizedDemo1.class) {
System.out.println(Thread.currentThread().getName() + " super start");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " super finished");
}
}
}
//子类,在子类的main方法中调用子类的synchronized方法,在method方法中调用父类的method方法,是可以执行父类的method方法的,
也就是说对于一个锁对象而言,这是传递过去的,也即在这个线程中这个锁是可以重复利用的,那么如果锁都不是同一个对象的话,自然也就不存在什么同步了(一开始没反应过来)
class Son extends SynchronizedDemo1{
public void method() throws InterruptedException {
synchronized(Son.class) {
System.out.println(Thread.currentThread().getName() + " son start");
Thread.sleep(3000);
super.method();
System.out.println(Thread.currentThread().getName() + " son finished");
}
}
public static void main(String[] args) {
Son s=new Son();
try {
s.method();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}