Two ways to create threads in Java

Source: Internet
Author: User

Way one: Extends Thread

Step: 1. Inherit the Tread class

2. Override the Run () method (in order to store the code to run for multithreading)

3. Create a subclass object for the thread class

4. Call the Start () method of the subclass object to start the thread

Method Two: Implements Runnable

Step: 1. Implement the Runnable interface

2. Overwrite the Run () method in the interface (used to encapsulate the code that the thread is running)

3. Creating thread objects from the thread class

4. Pass the object that implements the Runnable interface class as a parameter to the constructor of the thread class

5. Open the thread by calling the start () method of the Thread class

Why should there be a runnable interface?

Because the runnable interface can solve the limitations of single inheritance,

The Runnable interface is actually an abstraction of behavior, stripping out a behavior and setting it into an interface. The task object for the thread is being instantiated.

Two ways to create threads 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.