gpt4 book ai didi

java - 为什么不运行方法调用?

转载 作者:行者123 更新时间:2023-12-01 07:59:39 24 4
gpt4 key购买 nike

我写了以下示例:

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方法?

最佳答案

因为使用 Runnable 构造的线程的默认行为是委托(delegate)给作为参数传递给构造函数的 runnable。但是您在线程本身中重写了 run() ,因此它不是委托(delegate)给可运行对象,而是执行重写的 run() 方法内的代码。

郑重声明,这是您覆盖的 Thread.run() 的默认实现:

private Runnable target;

public void run() {
if (target != null) {
target.run();
}
}

关于java - 为什么不运行方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com