Java thread Creation

Source: Internet
Author: User

Java thread Creation

There are two ways to create a Thread in Java: one is to inherit the Thread class to create a Thread object (the Thread class also implements the Runnable interface), and the other is to implement the Runnable interface. The code for the first method is as follows:
Public class MyThread extends Thread {@ Override public void run () {// task to be completed by this Thread }}

After defining the threadMyThread thread = new MyThread ();To create a thread.Thread. start ();To start the thread.
In this way, you can add other attributes for the thread in the MyThread class, such as the thread name. However, Java is a single inheritance. If your primary class still needs to inherit other parent classes, this method is not suitable.
Let's look at the second method to create a thread:
Implement the Runnable interface. The Runnable interface has only one run method. When a class implements the Runnable interface, it must implement the run () method in the class. The run () method completes the functions completed by a specific thread.
The code snippet is as follows:

Public class MyThread2 implements Runnable {@ Override public void run () {// task to be completed by the thread }}

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.