探索2种创办多线程方法本质

探索2种创建多线程方法本质
下面代码的运行结果是什么:

package com;

public class start {

/**
 * @param args
 */
public static void main(String[] args) {
new threads(new Run()).start();
}



}

class Run implements Runnable{

@Override
public void run() {
System.out.println("runnable");
}

}

class threads extends Thread{

public threads(Run run){
super(run);
}

public void run(){
System.out.println("thread");
}
}
------解决思路----------------------
实际试了一下这个程序,,输出居然是thread,感觉很神奇。。

首先看看Thread类里面run函数的的说明
/**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
API文档李米娜说,有target,执行target的润函数;没有target,do nothing!!

按上面的程序,new threads(new Run()),,target应该是Run的一个实例,但是为什么没有执行Run类里面的run函数呢??
后来一想,调用层次是这样的:Thread绑定target之后,先调用Thread的run函数,在这个run函数里面调用target的run函数。
现在,class threads extends Thread,定义了一个继承Thread的类,问题是还会不会调用Thread的run函数??
明显不会,因为子类已经重写了父类的run函数

修改程序如下:
package com.test;

public class Test {
/**
 * @param args
 */
public static void main(String[] args) {
new threads(new Run()).start();
}

}



class Run implements Runnable{

@Override
public void run() {
System.out.println("runnable");
}

}

class threads extends Thread{

public threads(Run run){
super(run);
}

public void run(){
System.out.println("thread");
super.run(); //此处调用Thread的run函数
}
}

输出结果:
thread
runnable
------解决思路----------------------
就是考对多态的理解罢了。