自从我在 Java
中使用线程以来,我发现了这两种编写线程的方法:
使用实现可运行
:
public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
或者,使用扩展线程
:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
这两个代码块有什么显着差异吗?
最佳答案
是的:实现Runnable
是首选方法,IMO。您并没有真正专门化线程的行为。你只是给它一些运行的东西。这意味着composition是哲学上“更纯粹”的方法。
用实用术语来说,这意味着您可以实现Runnable
并从另一个类扩展......并且您还可以实现Runnable
从 Java 8 开始通过 lambda 表达式。
关于java - Java 中的 "implements Runnable"与 "extends Thread",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165160/