锁重入也支持父子类继承的环境。
类Main.java代码
package chapter2.test2_1.test2_1_8;
public class Main {
public int i = 10;
synchronized public void operateIMainMethod() {
try {
i--;
System.out.println("main print i=" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
子类Sub.java代码
package chapter2.test2_1.test2_1_8;
public class Sub extends Main {
synchronized public void operateISubMethod() {
try {
while (i > 0) {
i--;
System.out.println("sub print i=" + i);
Thread.sleep(100);
super.operateIMainMethod();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
自定义线程类MyThread.java代码
package chapter2.test2_1.test2_1_8;
public class MyThread extends Thread {
@Override
public void run() {
Sub sub = new Sub();
sub.operateISubMethod();
}
}
运行类Run.java代码
package chapter2.test2_1.test2_1_8;
public class Run {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
程序运行结果
此示例说明,当存在父子类继承关系时,子类是完全可以通过锁重入调用父类的同步方法
的