扩展Thread类的主要优点是什么

扩展Thread类的主要优点是什么

本文介绍了扩展Thread类的主要优点是什么(或何时扩展Thread而不是实现runnable)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出扩展Thread类的可能优点是什么?

I'm trying to find out what are the possible advantages of extending the Thread class would be?

这是我描述的另一个问题的一部分:
有两种在Java中创建线程的方法

This is a part of another question which I describe:There is two way of creating threads in Java


  1. 从Thread类扩展

  2. 实现runnable接口

随着的推出,使用runnable接口有几个好处。我的问题是从Thread类扩展的优势是什么?我想到的唯一优势是可以从Thread类扩展,让我们称之为ThreadExtended类。然后他/她可以在ThreadExtended中添加更多功能(我不知道它可能是什么),然后当他/她想要创建一个线程时,它不是从Thread类扩展而是从ThreadExtended扩展。

As expalined here there are several benefits of using runnable interface. My question is what is the advantage of extending from Thread class? The only advantage that comes to my mind is that one can extend from Thread class, and let's say call it ThreadExtended class. Then he/she can add more functionality in ThreadExtended(which I don't know what that might be), and then when he/she wants to create a thread, instead of extending from Thread class, it extends from ThreadExtended.

使用Thread类而不是Runnable接口有什么好处吗?您是否知道从Thread类扩展的任何类,然后要求用户从这些类扩展,如果他们想要具有多线程功能?

Is there any advantages in using Thread class instead of Runnable interface? Do you know any class(es) that extends from Thread class and then ask users to extends from those classes if they want to have multithreading capabilities?

    public class ThreadExtended extends Thread{
    //override some functions || add more functionality to Thread class
    }

    public class MyThread extends ThreadExtended{
     public void run()
    {
     for(int i=0;i<10;i++)
        {
          System.out.println("Using ThreadExtended instead of Thread directly");
        }
    }

    public static void main(String args[])
    {
    MyThread myThread = new MyThread();
    myThread.start();
    }
    }


推荐答案

那里扩展Thread类很少是一个令人信服的理由。我想在大多数情况下,你最终只会将所有做一些东西的逻辑投入到run方法中。

There is rarely a compelling reason to extend the Thread class. I would imagine that in most cases, you would end up just throwing all of your 'do some stuff' logic into the run method anyway.

你一定要坚持实施Runnable。通过选择扩展Thread,您创建的类层次结构可能是荒谬的,并且最终将限制您重构事物的选项。通过选择实现Runnable,你不需要实现者的血统,你可以使用强大的抽象,如,以抽象出运行一大块代码的细节。最后,更喜欢实现一个接口而不是扩展一个类是一个好习惯!

You should definitely stick with implementing Runnable. By choosing to extend Thread, you are creating a class hierarchy that probably is nonsensical and will wind up restricting your options for refactoring things in the future. By choosing to implement Runnable, you make no demands of what the lineage of the implementer is, and you can use powerful abstractions like the ExecutorService to abstract away the nuts and bolts of running a chunk of code. Finally, preferring to implement an interface rather than extend a class is a good practice!

这篇关于扩展Thread类的主要优点是什么(或何时扩展Thread而不是实现runnable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:42