我知道这是一件很小的事情,对于所有在这里的程序员来说都是很容易的,但是我很固执。我不明白为什么此代码段打印出“狗”而不是“猫”。
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();
调用start()
一个上Thread
对象导致JVM以生成一个新的系统螺纹,其然后前进到调用run
方法。其默认实现如下所示:
private Runnable target; // This is what you passed to the constructor
@Override
public void run() {
if (target != null) {
target.run();
}
}
由于您已经在匿名Thread
子类声明中重写了此方法,因此永远不会调用此代码,并且Runnable
根本不会使用注入的代码。
此外,只要有可能,就不要理会Thread
该类,Runnable
而是将代码放在s中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句