首先,通过测试得出结论是:同步不可以继承。
public class DemoSynchronizeExtends {
synchronized public void method(){
try {
System.out.println("main 下一步 sleep begin threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("main 下一步 sleep end threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SubDemoSynchronizeExtends extends DemoSynchronizeExtends {
public void method(){
try {
System.out.println("sub 下一步 sleep begin threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("sub 下一步 sleep end threadName="
+ Thread.currentThread().getName() + " time="
+ System.currentTimeMillis());
super.method();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ThreadA extends Thread{
private SubDemoSynchronizeExtends sub;
public ThreadA(SubDemoSynchronizeExtends subDemo){
this.sub = subDemo;
}
@Override
public void run() {
super.run();
sub.method();
}
}
public class ThreadB extends Thread{
private SubDemoSynchronizeExtends sub;
public ThreadB(SubDemoSynchronizeExtends subDemo){
this.sub = subDemo;
}
@Override
public void run() {
super.run();
sub.method();
}
}
public class TestDemo {
public static void main(String[] args) {
SubDemoSynchronizeExtends sub = new SubDemoSynchronizeExtends();
ThreadA threadA = new ThreadA(sub);
threadA.setName("A");
threadA.start();
ThreadB threadB = new ThreadB(sub);
threadB.setName("B");
threadB.start();
}
}
/*
* 测试结果
*/
sub 下一步 sleep begin threadName=A time=1539960054091
sub 下一步 sleep begin threadName=B time=1539960054092
sub 下一步 sleep end threadName=A time=1539960059092
main 下一步 sleep begin threadName=A time=1539960059092
sub 下一步 sleep end threadName=B time=1539960059093
main 下一步 sleep end threadName=A time=1539960064092
main 下一步 sleep begin threadName=B time=1539960064092
main 下一步 sleep end threadName=B time=1539960069093
由测试Demo发现同步是不能被继承的,但是为什么不能被继承呢?这个问题确实值得深入探讨。
要想彻底能明白原因应该先弄明白类继承到底是怎样的过程,这个问题后续再进行探讨