Two ways to create a thread in Java

Source: Internet
Author: User

Java provides threading class thread to create multithreaded programs. In fact, creating a thread is the same as creating an object of a normal class, and a thread is an instance object of the thread class or its subclasses. Each thread object describes a separate thread. To produce a thread, there are two ways of doing it:

You need to derive a new thread class from the Java.lang.Thread class, overloading its run () method;
Implement the Runnalbe interface, overloading the run () method in the Runnalbe interface.

Why should Java provide two ways to create threads? What are the differences between them? In comparison, which method is better?

In Java, a class only supports single inheritance, that is, when a new class is defined, it can only extend one external class. This way, if the custom thread class is created by extending the thread class, then the custom class cannot extend the other classes. It is not possible to implement more complex functions. Therefore, if your custom class must extend other classes, you can define the class as a threading class by using a method that implements the Runnable interface, which avoids the limitations of Java single inheritance.

It is also important that threads created with the implementation of the Runnable interface can handle the same resource, thus sharing resources.

Two ways to create a thread in Java

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.