为了账号安全,请及时绑定邮箱和手机立即绑定

关于Java当中继承的疑问

关于Java当中继承的疑问

白衣染霜花 2019-01-19 06:21:03
这是我运行的Test.java文件的源码,Sub类继承的是Main类,MyThreadA和MyThreadB都是线程类 package service; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Sub subRef = new Sub(); MyThreadA a = new MyThreadA(subRef); a.setName("A"); a.start(); MyThreadB b = new MyThreadB(subRef); b.setName("B"); b.start(); } } 如下是控制台的运行结果,我的疑问是为什么Main类里面的serviceMethod()方法也被调用了?线程MyThreadA和线程MyThreadB的run()方法不是只是调用了Sub类里面的serviceMethod()方法吗? int sub 下一步 sleep begin threadName=A time=1521894980829 int sub 下一步 sleep begin threadName=B time=1521894980829 int sub 下一步 sleep end threadName=A time=1521894985834 int sub 下一步 sleep end threadName=B time=1521894985834 int main 下一步 sleep begin threadName=A time=1521894985835 int main 下一步 sleep end threadName=A time=1521894990838 int main 下一步 sleep begin threadName=B time=1521894990838 int main 下一步 sleep end threadName=B time=1521894995840 如下是MyThreadA类 package service; public class MyThreadA extends Thread { private Sub sub; public MyThreadA(Sub sub) { super(); this.sub = sub; } @Override public void run() { // TODO Auto-generated method stub sub.serviceMethod(); } } 如下是MyThreadB类 package service; public class MyThreadB extends Thread { private Sub sub; public MyThreadB(Sub sub) { super(); this.sub = sub; } @Override public void run() { // TODO Auto-generated method stub sub.serviceMethod(); } } 如下是Main类 package service; public class 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 (Exception e) { // TODO: handle exception e.printStackTrace(); } } } 如下是Sub类,继承Main类 package service; public class Sub extends Main { @Override 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 (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
查看完整描述

2 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

去掉super.serviceMethod();

查看完整回答
反对 回复 2019-03-01
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

基本概念都没有搞清楚,就去学线程合适吗?

查看完整回答
反对 回复 2019-03-01
  • 2 回答
  • 0 关注
  • 427 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信