7. Learning Thread

Source: Internet
Author: User
Tags inheritance thread class

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, looking forward to communicating with you. -------

Sometimes multiple actions need to be performed at the same time, and multithreading is used.

Concurrent programs divide programs into separate tasks that are separate from one other.

A thread is a single sequential control flow in the process.

A single process can have multiple tasks that execute concurrently.

You can define threads in two ways:

1. Inherit the thread class:

1. Define class inheritance Thread

2. The run () method of the replication thread

3. Start () of the calling thread

Class Demo Extendsthread {

public void Run () {

}

}

2. Implement Runnable interface

1. Define class implementation Runnable interface

2. Overwrite the Run () method in the Runnable interface

3. Create an object from the thread class

4. Pass the sub-object of the Runnable interface as the actual parameter to the constructor of the thread class

5. Call the Start () method of the thread class to open the thread and invoke the Run method in the Runnable interface subclass

Class Demoimplements Runnable {

public void Run () {

}

}

The second approach is good because it avoids the limitations of single inheritance, and it is recommended to use implementations.

The lock of a synchronized code block is any object

The lock of the synchronization function is the this pointer

The lock of a static synchronization function is a class object

By looking at the API documentation, you can know the various methods in the Runnable interface and thread, and use it in practice.

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.