Java 学习笔记之 父子类Synchronized
父子类Synchronized:
我们通过一个例子来验证下,父类和子类的Synchronized方法被同时调用,是否是同步的。
public class FatherClass {synchronized public void callFather(){
try {
System.out.println("------------Call Father start------");
Thread.sleep(10000);
System.out.println("------------Call Father end------");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class SunClass extends FatherClass {
synchronized public void callSon(){
try {
System.out.println("------------Call Son start------");
Thread.sleep(10000);
System.out.println("------------Call Son end------");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class FatherThread extends Thread {
private FatherClass f;
public FatherThread(FatherClass f) {
this.f = f;
}
@Override
public void run() {
super.run();
f.callFather();
}
}
public class SunThread extends Thread {
private SunClass s;
public SunThread(SunClass s) {
this.s = s;
}
@Override
public void run() {
super.run();
s.callSon();
}
}
public class ThreadRunMain {
public static void main(String[] args) {
testSyncFSThread();
}
public static void testSyncFSThread(){
SunClass sc = new SunClass();
SunThread st = new SunThread(sc);
st.start();
FatherThread ft = new FatherThread(sc);
ft.start();
}
}
运行结果:
通过验证,回答是Yes。
以上是 Java 学习笔记之 父子类Synchronized 的全部内容, 来源链接: utcz.com/z/389965.html