Two ways to implement multithreading in Java

Source: Internet
Author: User

Two ways to implement multithreading:

Mode 1: Inherit the thread class

A: Custom Mythread class inherits the thread class

B: Rewrite run () in the Mythread class

C: Create an object of the Mythread class

D: Start the Thread object.

Problem:

A. Why would you want to rewrite the Run method?

The run () method encapsulates code that is executed by the thread

B. Which method is used to start the thread object?

Start () method

C. What is the difference between the run () and start () methods?

Calling the Run method directly is just a normal method call

Calling the Start method starts the thread before the JVM calls the run () method

Method 2: Implement the Runable interface

A: Custom class myrunnable Implementation Runnable interface

B: Overriding the Run method in the Myrunnable class

C: Create an object of the Myrunnable class

D: Create the object of the thread class and pass the object in C step as a constructor parameter.

Benefits of implementing Interface inheritance:

Avoid limitations due to Java single inheritance

Suitable for multiple same program code to deal with the same resource situation, the thread with the program code, data effectively separated, better realize the object-oriented thinking

Two ways to implement multithreading 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.