Creation and basic use of Java threads

Source: Internet
Author: User

Creation of Threads

1. Two ways to create a thread

(1) Create a subclass of thread and overwrite the run () method

(2) Implement Runnable interface

Ways to create multithreading

Method 1: implement multi-threading by creating a subclass of the thread class, steps like this:

1. Define a subclass of the thread class.

2. Define a method in the subclass run (), overwriting the method run () in the parent class.

3. Create a thread object for the subclass.

4. Start the thread with the start () method.

Note :

1. Each thread will start and each thread will run until it is complete.

2. A series of threads starting in some order does not mean that they will be executed in that order.

3. For any thread that starts, the scheduler cannot guarantee its execution order, and the duration is not guaranteed.

4. When the thread target run () method ends, the thread finishes

Method 2: Create multi-Threading through an interface, with the following steps:

1. Define a class that implements the Runnable interface.

2. Define the method run (). The runnable interface has an empty method run (), and the class that implements it must override this method.

3. Create a thread object for the class, and pass the object as a parameter to the constructor of the thread class to produce an object of the thread class. Watch this step!

4. Start the thread with the start () method.

Note : Because Java does not allow multiple inheritance, the first method can only be used if the class does not extend any other class. Therefore, for many extension classes that are already other classes (such as applet programs), only the second method can be used to create threads.

Creation and basic use of Java threads

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.