实际试了一下这个程序,,输出居然是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
/**
* 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
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货