Synchronized同步是否具有继承性,及其原因剖析

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010612373/article/details/83280491

首先,通过测试得出结论是:同步不可以继承。

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发现同步是不能被继承的,但是为什么不能被继承呢?这个问题确实值得深入探讨。

要想彻底能明白原因应该先弄明白类继承到底是怎样的过程,这个问题后续再进行探讨

展开阅读全文

没有更多推荐了,返回首页