简体   繁体   English

性能明智,可以更快地实现Runnable或扩展Thread类

[英]Performance wise which is faster implementing Runnable or extending a Thread class

We can create a thread using Implementing Runnable or by extending a thread class. 我们可以使用Implementing Runnable或通过扩展线程类来创建线程。 Can anyone tell me performance wise which is faster implementing a Runnable or extending a Thread class and Why? 谁能告诉我性能方面的明智选择,那就是更快地实现Runnable或扩展Thread类,为什么? Also I know while implementing Runnable we can implement more Interfaces and also extend a class. 我也知道在实现Runnable时,我们可以实现更多接口,也可以扩展一个类。 Extending a class is something we lose out if we directly extend a Thread class. 如果直接扩展Thread类,扩展类是我们会失去的东西。 But is there any performance difference in both scenarios 但是这两种情况下的性能是否存在差异

Performance-wise there is no difference between the two. 在性能方面,两者没有区别。 Yet using "implements Runnable" is preferable because it gives you more freedom(extending another class,...) and the same object is shared across multiple threads(which also reduces the used memory). 但是最好使用“可运行的实现”,因为它给您更多的自由(扩展另一个类,...),并且同一对象在多个线程之间共享(这也减少了使用的内存)。

It depends (as always): 它取决于(一如既往):

  • If you would run it only once, the Thread extension has no drawback except it is not as flexible and harder to test (eg in a unit test). 如果只运行一次,则Thread扩展没有缺点,只是它不那么灵活且难以测试(例如在单元测试中)。
  • If you want to run it more often, the Runnable is more flexible as you can pass it to an Executor using a thread pool. 如果您想更频繁地运行它,那么Runnable会更加灵活,因为您可以使用线程池将其传递给Executor By doing so you would get a better performance as the overhead of thread creation for each execution will be dropped. 这样,您将获得更好的性能,因为将减少每次执行创建线程的开销。

If you implement a Runnable you have various ways to execute the code (synchronous in a unit test, using an executor, or even wrap it with a Thread anyway). 如果实现了Runnable ,则有多种执行代码的方法(在单元测试中同步,使用执行程序,或者无论如何都用Thread包装)。 And the pure thread extension never has a better performance, it can be equal only. 而且纯线程扩展永远不会有更好的性能,它只能相等。 Implementing Runnable only is always the better option also by allowing multiple interfaces or using an independent inheritance, it is simply the better design. 通过允许多个接口或使用独立的继承,仅实现Runnable总是更好的选择,这只是更好的设计。 Following this I would never extend Thread . 在此之后, 我将不再扩展Thread

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM