Java multithreading and Java Multithreading

Source: Internet
Author: User

Java multithreading and Java Multithreading

Java supports multithreading in two ways.

 

 

First -- Inherit the Thread class and override the run Method

 

Steps:

 

Instance:

Public class MyThread extends Thread () {@ Override public void run () {// multithreading code} // other code}
Thread t = new MyThread();t.start();

 

 

Second: implement the Runnable interface, and construct the Thread class with the object of this class.

 

Steps:

 

Instance:

Public class MyClass implements Runnable () {public void run () {// multithreading code} // other code}
MyClass m = new MyClass();Thread t = new Thread(m);t.start();

 

 

Functions of the start Method

 

 

Why can we implement multithreading in the above two ways?

 

The first method is easy to understand. Since the run method of the Thread class is rewritten, after the start method is called to start the Thread, jvm will call the run method rewritten by the subclass;

For the second method, after the start method is called to start the Thread, jvm will call the run method of the Thread class. The Code is as follows:

public void run() {    if (target != null) {        target.run();    }
}

Specifically, target is a member variable of the Thread class and its type is Runnable. When the Runnable object is used to construct a Thread, the target will reference this interface object. Therefore, when target. run () is executed, the run method of the interface object is actually executed.

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.