public class Explorer3 {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
System.out.print("Cat");
}
};
Thread t = new Thread(r) {
public void run() {
System.out.print("Dog");
}
};
t.start();
}
}我知道比如new Thread(Runnable r).start()的时候,是调用target的run方法,即Runnable r中的run方法
而直接new Thread().start()时候,调用的是thread类中的run()方法可这题中调用的结果是Thread中的run,即输出Dog,而为何不调用Runnable中的run输出Cat呢?
解决方案 »
- 急!(生产者消费者问题)为什么产品总数会大于5
- 你还在用jdk1.4吗?
- 请问如何打包,运行程序啊?
- 单独的使用mybatis 怎么来管理事务
- 求助 JCreator 中如何加入"watch" 查看变量值?
- 请教一个线程的问题
- 来者有分
- 配置问题,请教了*************************************************
- 什么地方有JDK下呢??应该怎么用呢?什么JAVA工具对一个初学者好呢??
- 一个合理化建议!
- 求java高手 帮忙解决一下问题,给定对象的具体属性值,从一个容器,取出具体对象的算法
- 有哪位大哥用java写过斗地主的,小弟想要用java写个斗地主,有些问题想要请教
System.out.println("Dog");
}
};
这里你是使用的继承机制实现的线程,而且重写了run()方法,根据多态机制,自然是调用你在子类中重写的run()方法。如果你不使用继承机制,而使用
Thread t = new Thread(r);
这时候自然是调用Thread中的run()方法。
Thread中的run实现方式是:
public void run() {
if (target != null) {
target.run();
}
}这里的target是通过new Thread(r);里的r赋值而来。
因此,只要传入了参数Runnable r,调用的就是接口实现类中的run()方法。如果没有传入参数r,也就不执行任何功能了。
这不是以谁为准的问题,也不用死记,把流程弄明白就可以了。
调用实现Runnable接口的类的run方法。
public interface RunTest { void run();
}
2】
public class RunTestImpl implements RunTest { public RunTest target;
public RunTestImpl(RunTest target){
this.target=target;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("I was called!");
if(target!=null){
target.run();
}
}}
3】
public class Test1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RunTest t1=new RunTest() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("my runtest");
}
};
RunTestImpl t2=new RunTestImpl(t1);
RunTestImpl t3=new RunTestImpl(t1){
public void run() {
// TODO Auto-generated method stub
System.out.println("myimpl runtest");
}
};
System.out.println("t2:");
t2.run();
System.out.println("t3:");
t3.run();
}}
//OUTPUT:
t2:
I was called!
my runtest
t3:
myimpl runtest
public class ThreadTest { /**
* @param args
*/
public static void main(String[] args) { MyRunnable t=new MyRunnable();
Thread t1=new Thread(t);
t1.start();
MyThread myThread=new MyThread(t);
myThread.start();
}}
class MyThread extends Thread{
public void run(){
System.out.println("Mythread!");
}
public MyThread(Runnable t){
super(t);
}
}
class MyRunnable implements Runnable{ @Override
public void run() { System.out.println("Myrunnable!");
}
}
------------------------------------------------------------------
result:
Myrunnable!
Mythread!
new Thread(r).start();
一下咋运行啊~~~