为什么“实现Runnable”优先于“延伸线程”? [英] Why "implements Runnable" is Preferred over "extends Thread"?

查看:115
本文介绍了为什么“实现Runnable”优先于“延伸线程”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 线程本身实现了Java Runnable !根据互联网上的大多数专家的说法,实现Runnable比扩展线程更受欢迎!即使我们也无法使用Runnable ,因为线程意义上没有Thread类!

那么为什么我们更喜欢实现 Runnable 而不是扩展 Thread ,因为在这两种情况下都是实际的线程通过调用 Thread 实现的方法(即 start() run()来说明)虽然在 Thread 的情况下,我们并没有真正扩展 Thread 的功能只是重写 run()方法?

The Java Thread itself implements a Java Runnable! and according to most of the experts over Internet, implements Runnable is preferred over extends Thread! even though we cannot use utilize Runnable in the sense of thread with out the Thread class!
Then why do we prefer to implement Runnable over extending Thread since in both cases the actual thread is stated by calling a Thread implemented method (i.e. start() or run()) although in case of Thread we are not truly "extending" the functionality of Thread by merely overriding the run() method?

如果我听起来有点混乱,我道歉......!

I apologies if I sound confusing..!

推荐答案

最常见的区别是:

当你扩展Thread类时,你可以不扩展您需要的任何其他课程。 (如您所知,Java不允许继承多个类)。当您实现Runnable时,您可以为您的类保存一个空间,以便将来或现在扩展任何其他类。

When you extend Thread class, you can’t extend any other class which you require. (As you know, Java does not allow inheriting more than one class). When you implement Runnable, you can save a space for your class to extend any other class in future or now.

然而,显着的区别是。

当您扩展Thread类时,每个线程都会创建唯一对象并与之关联。当您实现Runnable时,它将同一个对象共享给多个线程。

When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.

检查:
http://manikandanmv.wordpress.com/tag/extends-thread-vs-implements-runnable/

这篇关于为什么“实现Runnable”优先于“延伸线程”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆