当子类从线程父类扩展时,我们是否重写 run 方法
当我们子类化Thread时,我们是否重写它的run方法?我们知道Thread类本身实现了Runnable,但是Runnable类中没有定义run方法的主体。
这是我脑海中的画面:
Runnable - 父类 - 它有一个 run 方法,主体为空。
Thread- Child,
classA 扩展了 Thread- Child of Child,
当我们在“classA”中定义 run() 方法时,我们是否覆盖了 Runnable 类中声明的 run 方法? 感谢您抽出时间。
When we Subclass Thread, do we override its run method? We know Thread class itself implements Runnable, but there is no body for run method defined in Runnable class.
This is picture in my mind:
Runnable - Parent class-it has a run method in it, with empty body.
Thread- Child,
classA extends Thread- Child of Child,
when we define run() method in "classA" , are we overriding run method declared in Runnable class?
Thank you for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种方法可以定义线程的行为:子类化 Thread 类,或者实现 Runnable 接口。
对于第一种方法,只需扩展 Thread 类并使用您自己的实现覆盖 run() 方法:
但是,实现 Thread 逻辑的首选方法是创建一个实现 Runnable 接口的类:
实现 Runnable 的原因首选的是它在线程的行为和线程本身之间提供了清晰的分离。例如,当使用线程池时,您实际上从未从头开始创建线程,您只需将 Runnable 传递给框架,它就会在可用线程上为您执行它:
进一步阅读:
There are two ways to define the behavior of a thread: subclass the Thread class, or implement the Runnable interface.
For the first way, simply extend the Thread class and override the run() method with your own implementation:
However, the preferred way of implementing the logic for a Thread is by creating a class that implements the Runnable interface:
The reason that implementing Runnable is preferred is that it provides a clear separation between the behavior of the thread and the thread itself. For instance, when using a thread-pool you never actually create the thread from scratch, you just pass a Runnable to the framework and it'll execute it on an available thread for you:
Further Reading:
只有当您要重写线程的功能或提高其性能时,才应该扩展线程。
接口告诉您,如果您使用此接口,您将获得功能。在您的情况下,您的业务逻辑需要在线程中运行然后使用接口。
如果您有更好的方法来有效地运行线程,那么请扩展线程。
You should extend the Thread , only when are you going to rewrite the functionality of thread or improve its performance .
Interface tells you that , if you use this interface , you will get the funcationality.In your case , your buisness logic needs to be run in a thread then use interface.
If you a better way of running thread efficiently then extend the Thread.