“实现可运行"vs “扩展线程"在 Java 中 [英] "implements Runnable" vs "extends Thread" in Java
问题描述
从我在 Java
中使用线程开始,我发现了以下两种编写线程的方法:
From what time I've spent with threads in Java
, I've found these two ways to write threads:
使用实现Runnable
:
With implements Runnable
:
public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
或者,使用扩展Thread
:
Or, with extends Thread
:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
这两个代码块有什么显着差异吗?
Is there any significant difference in these two blocks of code?
推荐答案
是:实现 Runnable
是首选方式,IMO.您并没有真正专注于线程的行为.你只是给它一些东西来运行.这意味着组合在哲学上是更纯粹"的.路要走.
Yes: implements Runnable
is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.
在实际术语中,这意味着您可以实现 Runnable
并从另一个类扩展......并且您还可以实现 Runnable
通过 Java 8 中的 lambda 表达式.
In practical terms, it means you can implement Runnable
and extend from another class as well... and you can also implement Runnable
via a lambda expression as of Java 8.
这篇关于“实现可运行"vs “扩展线程"在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!