Threading Problems in Java (iii)--the difference between inheriting thread VS implementing runnable

Source: Internet
Author: User
Tags thread class

from the Java design point of view, to create threads by inheriting the thread or implementing the Runnable interface is essentially no different, from the JDK help document we can see that the thread class itself implements the Runnable interface , If you must say what the difference is, summarize the points :

with the implementation Features of the Runnable interface

1, using the method of implementing Runnable interface to create objects can avoid the limitations of Java single inheritance mechanism;

2, with the implementation of the Runnable interface method, multiple threads can be implemented to share the same piece of code (data);

It is therefore recommended that if your program has synchronous logic requirements, use the Runnable method to create a thread.

In addition, each thread object can only start one thread:

1 /**2 * Features: Considerations for using Threads3 * You cannot use start to start the same thread 2 times regardless of inheriting thread or implementing the Rnunable interface4  */5  Public classTHREAD04 {6      Public Static voidMain (string[] args) {7Cat cat1=NewCat ();8 Cat1.start ();9         //Cat1.start (); same thread, cannot start 2 timesTen          OneDog dog1=NewDog (); AThread t=NewThread (DOG1); - T.start (); -         //T.start (); same thread, cannot start 2 times the     } - } -  - //Cat Class + classCatextendsthread{ -      Public voidrun () { +System.out.println ("11"); A     } at } -  - //Dog Class - classDogImplementsrunnable{ -      Public voidrun () { -System.out.println ("2"); in     } -}

Threading Problems in Java (iii)--the difference between inheriting thread VS implementing runnable

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.