为什么不运行方法调用?

时间:2014-10-05 14:11:50

标签: java multithreading

我写了以下示例:

public class MyThread extends Thread{
    MyThread(Runnable r){
        super(r);
    }
    public void run(){
        System.out.println("run");
    }
}
public static void main(String[] args) 
{
    Thread t = new MyThread(new Runnable() {
        @Override
        public void run() {
            System.out.println("rrrrrrrrrruuuuuuuuuuuun");
        }
    });
    t.start(); //run
} 

为什么调用MyThread中定义的run方法?

2 个答案:

答案 0 :(得分:3)

因为MyThread.run未覆盖,但Runnable.run是。现在,如果您查看MyThread.run的实施,则存储的Runnable不会参与其中。换句话说,使用构造函数给出了什么样的可运行性并不重要。你应该使用:

public static void main(String[] args) 
{
    Thread t = new MyThread() {
        @Override
        public void run() {
            System.out.println("rrrrrrrrrruuuuuuuuuuuun");
        }
    });
    t.start(); //run
} 

正如@BorisTheSpider所指出的那样,覆盖Thread通常不是一种好的做法:Thread有责任启动Thread并控制runnable。更好的实施方式是:

public static void main(String[] args) 
{
    Thread t = new Thread(new MyThread() {
        @Override
        public void run() {
            System.out.println("rrrrrrrrrruuuuuuuuuuuun");
        }
    }));
    t.start(); //run
} 

答案 1 :(得分:3)

因为使用Runnable构造的线程的默认行为是委托给作为参数传递给构造函数的runnable。但是你在线程本身中覆盖了run(),所以它不是委托给runnable,而是在被覆盖的run()方法中执行代码。

对于记录,这里是你覆盖的Thread.run()的默认实现:

private Runnable target;

public void run() {
    if (target != null) {
        target.run();
    }
}
相关问题