1. 程式人生 > >Java多執行緒10:同步不具有繼承性

Java多執行緒10:同步不具有繼承性

父類的同步操作子類是不可以繼承獲得的

package unit2;

public class Demo8_tongbubujujichengxing {
	
	public static void main(String[] args) {
		Demo8_Sub subRef = new Demo8_Sub();
		Demo8_MyThreadA a = new Demo8_MyThreadA(subRef);
		a.setName("A");
		a.start();
		Demo8_MyThreadB b = new Demo8_MyThreadB(subRef);
		b.setName("B");
		b.start();
	}
}

class Demo8_Main {
	synchronized public void serviceMethod() {
		try {
			System.out.println("int main 下一步 sleep begin threadName="
					 + Thread.currentThread().getName() + " time="
					  + System.currentTimeMillis());
			Thread.sleep(5000);
			System.out.println("int main 下一步 sleep end threadName="
					 + Thread.currentThread().getName() + " time="
					 + System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Demo8_Sub extends Demo8_Main {
	public void serviceMethod() {
		try {
			System.out.println("int sub 下一步 sleep begin threadName="
					 + Thread.currentThread().getName() + " time="
					  + System.currentTimeMillis());
			Thread.sleep(5000);
			System.out.println("int sub 下一步 sleep end threadName="
					 + Thread.currentThread().getName() + " time="
					 + System.currentTimeMillis());
			super.serviceMethod();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Demo8_MyThreadA extends Thread {
	private Demo8_Sub sub;
	public Demo8_MyThreadA(Demo8_Sub sub) {
		super();
		this.sub = sub;
	}
	
	public void run() {
		sub.serviceMethod();
	}
}

class Demo8_MyThreadB extends Thread {
	private Demo8_Sub sub;
	public Demo8_MyThreadB(Demo8_Sub sub) {
		super();
		this.sub = sub;
	}
	
	public void run() {
		sub.serviceMethod();
	}
}

在這裡插入圖片描述 由以上實驗可知:子類中的方法在多執行緒中是非同步執行的,而父類中的方法時同步執行的。