多线程的 start() , run() ,执行顺序

hzc543806053 2012-05-06 04:17:18
class MyThread extends Thread{ 
public void run(){
System.out.println("MyThread: run()");
}
public void start(){
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable{
public void run(){
System.out.println("MyRunnable: run()");
}
public void start(){
System.out.println("MyRunnable: start()");
}
}
public class MyTest {
public static void main(String args[]){
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}


求解释为什么输出:

F:\>java MyTest
MyThread: start()
MyRunnable: run()
...全文
462 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
xlhb 2012-05-06
  • 打赏
  • 举报
回复
首先说第一个线程MyThread启动:因为MyThread类重写了start方法。所以启动时自然执行重写的方法。
再说第二个MyRunnable类,他不是线程,只是实现了线程需要的一个接口,而Thread线程类有它自己的start方法(它里面默认只调用run方法,),所以利用实现接口而得的线程thread掉用start方法,只看到类MyRunnalble中的run方法。所以执行结果是MyRunnable: run()
myisfei 2012-05-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
MyThread重写了start方法,所以它的run方法不会被执行

MyRunnable不是线程,真正的线程是new Thread(MyRunnable),所以会MyRunnable的run函数
[/Quote],
赞同此说法,但是
MyRunnable是线程,但线程没有启动,
logic_well 2012-05-06
  • 打赏
  • 举报
回复
这跟线程关系不大
也没什么顺序问题
这里牵扯的问题就如上边那位仁兄所说:一个是子类重写父类方法,重写后的start()显然是没有启动run()方法的能力的;二就是利用接口参数来构造一个线程的多态的展现,这里的MyRunnable只是作为一个参数,实际new的是一个Thread,所以thread的start()方法自然就是Thread类里那个用来启动线程的 start()方法
feihumingyue 2012-05-06
  • 打赏
  • 举报
回复
由于你的start()方法已经重写,所以start()只能被视为一般的方法被调用,如只输出了:MyThread: start(),不能引出MyThread:run();MyRunnable只是在自己内部重写了start()方法,而启动一个线程是有Thread的start方法,因此可以运行出MyRunnable:run().

个人拙见,仅供参考
sdojqy1122 2012-05-06
  • 打赏
  • 举报
回复
private Runnable target;

public void run() {
if (target != null) {
target.run();
}
}
如果没传参数runnble,run()方法里什么也没执行。
如果传了参数执行 target 的 run()方法。
至于start()方法,没有用到target。
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0 || this != me)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
周靖峰 2012-05-06
  • 打赏
  • 举报
回复
MyThread重写了start方法,所以它的run方法不会被执行

MyRunnable不是线程,真正的线程是new Thread(MyRunnable),所以会MyRunnable的run函数

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧