java - 使用继承和多态来实例化 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();
解决方案
线程的实例化完全没有区别。唯一的区别在于保存对线程的引用的变量的类型。
第一个问题:你了解对象和对对象的引用之间的区别吗?变量不是对象,它包含一个引用。
所以问题是,您希望您的程序将线程视为一般线程(第一个示例)还是另一个线程(第二个示例)?这两个都是有效的,它只取决于你想要完成什么。一般情况下,如果后续代码不需要专门把它当作AnotherThread处理,那么优先编程到Thread接口。
推荐阅读
- flutter - 如何从颤动的模态底部表中获取数据?
- validation - Yii2 - 没有 $form->field() 的 AJAX 验证
- kubernetes-helm - 使用 Kubernetes Ingress Nginx 的 GRPC 服务器没有响应
- git - 如何将 ssh 密码添加到 Docker 并在使用后将其删除?
- powershell - 如何在备份脚本期间记录复制的项目?
- delphi - 在 RTL 系统上强制英语语言任务对话为 LTR
- gradle - 限制梯度传递深度分辨率
- reactjs - 带有 React 和 WebSockets 的仪表板 - 如何构建应用程序
- asp.net-core - 如何使用 SignalR 在 ASP.Net Core 中实现屏幕共享和查看?
- regex - Clickhouse 查询使用正则表达式