我有如下三个类:
1.线程实例
public class ThreadInstance extends Thread {
public ThreadInstance()
{
}
public ThreadInstance(RunnableInstance r) {
super(r);
}
public void run() {
System.out.println("|Extend|");
}
}
2.Runnable实例
public class RunnableInstance implements Runnable {
public void run() {
System.out.println("|Implement|");
}
}
3.客户端
public class Client{
public static void main(String[] args) {
new ThreadInstance(new RunnableInstance()).start();
}
}
OUTPUT 打印|扩展|而不是 |实现|
在客户端类中,通过传递一个可运行的实例来创建一个线程。因此,当该线程运行时,应调用 Runnable 类(RunnableInstance)的 run() 方法。但是在上面的例子中,调用了 ThreadInstance 的 run() 方法。
我不是很清楚这背后的原因。任何人都可以说明我在这里缺少什么。我还检查了 Thread 类的 run() 方法,发现如果检查 runnable 实例是否不为 null,则它会调用 Runnable 类的 run() 方法。
最佳答案
i checked the run() method of Thread class and found that […] it calls run() method from Runnable class
您已经覆盖了 run
方法,因此您的 ThreadInstance
不再执行此操作。
您需要选择其中之一。 要么覆盖Thread
中的run
,要么 将Runnable
传递给它。两者都不是。
从技术上讲,可以执行以下操作:
public class ThreadInstance extends Thread {
public ThreadInstance() {}
public ThreadInstance(RunnableInstance r) { super(r); }
public void run() {
super.run(); // note
System.out.println("|Extend|");
}
}
但这可能不是一个好主意,除非您真的知道自己在做什么。我们通常不应该改变 Thread
的行为。
另见:
关于java - 将 Runnable 实例传递给 Thread 调用 Thread 子类的 run() 而不是 Runnable 类的 run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448715/