Why “implements Runnable” is Preferred over “extends Thread”? [duplicate]

佐手、 提交于 2019-11-28 06:20:59

The most common difference is:

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.

However, the significant difference is.

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.

Check this: http://manikandanmv.wordpress.com/tag/extends-thread-vs-implements-runnable/

If your class is extending the Thread class then it becomes a single thread which inherits the properties Thread class, so it'll be heavy. (When extending Thread class each of the threads creates unique object and associate with it, but when implementing Runnable, it shares the same object to multiple Threads).

If your class is Implementing the Runnable interface then you only override the run() .So this instance creates a separate Thread and every individual Thread runs separately but not as a single heavy Thread in your program. Another thing, Since Java does not support multiple inheritance, if you implement the Runnable you'll avoid problems of multiple extending, so if you implement Runnable interface you can extend any class that you are required other than Thread class.

A class may only have one superclass, but may implement any number of interfaces. By extending Thread you give up the opportunity to subclass anything else.

Java only allows single inheritance, which means that if you inherit from Thread you won't be able to inherit from any other class. Implementing the Runnable interface doesn't have this limitation, since your class is allowed to implement any number of interfaces.

you really sound confuse.Anyway one reason i know that as we can achieve the same functionality using Runnable, so we should go for it because if we will implement Runnable then we can extend other class which is not possible if we will extend Thread class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!