我写了以下示例:
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方法?
答案 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();
}
}