协慌网

登录 贡献 社区

Java 中的 “实现 Runnable” 与“扩展线程”

从我在 Java 中使用线程的时间开始,我发现了这两种编写线程的方法:

使用implements Runnable

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call

或者,使用extends Thread

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call

这两个代码块有什么显着差异吗?

答案

1
88250
贡献值 86
贡献次数 1

据说:

仅在你要覆盖某些行为时使用继承。

更确切地说,可以理解为:

少用继承,多用接口。