首页 > 解决方案 > 使用继承和多态来实例化 Thread 子类的对象的主要区别是什么?

问题描述

当我们有一个诸如 AnotherThread 之类的类并且它扩展 Thread 并且我们在其中覆盖 run 方法时,多线程中以下两个代码之间的主要区别是什么。我们什么时候需要使用多态性来创建 AnotherThread 类的实例?当我们必须使用继承来创建另一个线程类时?

这是 Thread 的子类:

public class AnotherThread extends Thread{

    @Override
    public void run() {
        System.out.println("Hello from another thread.");
    }
}

在这段代码中,为什么我们使用多态性来实例化 AnotherThread 类的对象,其中 AnotherThread 是 Thread 的子类:

public static void main(String[] args) {

    System.out.println("This is the main thread.");


    Thread anotherThread = new AnotherThread();
    anotherThread.start();

在这段代码中,为什么我们使用继承来实例化 AnotherThread 类的对象,其中 AnotherThread 是 Thread 的子类:

public static void main(String[] args) {

    System.out.println("This is the main thread.");

    AnotherThread anotherThread_2 = new AnotherThread();
    anotherThread_2.start();

标签: javamultithreadinginheritancejava-8polymorphism

解决方案


线程的实例化完全没有区别。唯一的区别在于保存对线程的引用的变量的类型。

第一个问题:你了解对象和对对象的引用之间的区别吗?变量不是对象,它包含一个引用。

所以问题是,您希望您的程序将线程视为一般线程(第一个示例)还是另一个线程(第二个示例)?这两个都是有效的,它只取决于你想要完成什么。一般情况下,如果后续代码不需要专门把它当作AnotherThread处理,那么优先编程到Thread接口。


推荐阅读