Introduction to multithreading in the beauty of Java [from cainiao to masters]

Source: Internet
Author: User

Starting from this article, I will conduct an in-depth analysis on Java multithreading. This is a large part of the content, and it is also a hurdle that we must cross as Java developers! Because Java itself is a multi-threaded language, to really master Java, Please Master multithreading first! The article will be organized into a series containing several articles, because in my opinion, the problem of multithreading cannot be clearly described in several articles. Maybe the theoretical knowledge is not so exaggerated, however, there will be many actual situations. I will start from the basic concepts and step into it, and strive to make it easy for readers at different levels to understand with the simplest expressions! This chapterThe beauty of Java [from cainiao to masters] SeriesIntroduction to multithreading. In this chapter, I will guide you through Java multi-threaded development in terms of logic. The entire series will be a learning process from theory to practice!

If you have any questions during reading, please contact egg in time.

Mailbox: xtfggef@gmail.com Weibo: http://weibo.com/xtfggef

Reprint please explain the source: http://blog.csdn.net/zhangerqing

I. Introduction to multi-thread programming

1. Why do I need multi-thread programming?

We know that our computer is basically based on the X86 architecture, while the x86-based machine clock speed is only 4 GHz. With the advent of the information age, we need to process more and more data, therefore, the program performance requirements are getting higher and higher, improving the program performance. On the one hand, you need to improve the configuration of the runtime environment, that is, configure machines with better performance and faster CPU and larger memory, on the other hand, it is to optimize our own programs. From the perspective of the former, we say that the CPU clock speed of the current computer is close to the top level, and it is impossible to increase the CPU speed for a period of time, that is to say, it is a bad option to speed up program running by improving machine performance, because you need to invest more hardware. At the same time, when our program is running, the CPU is mostly idle, because the program not only has CPU scheduling, but most of the time-consuming operations are on Io, we know that the running speed of the program depends on the working principle of the barrel, and it is useless for the CPU to keep up with IO faster. Therefore, we need to properly utilize the idle CPU. When I/O is processing other resources, the CPU can continue to work. This is multi-thread programming. To sum up the advantages of multi-threaded programming, we can reasonably use the idle time of the CPU to improve program performance. One of my favorite words is: with multi-threaded programming, we can say goodbye.Moore's LawIn this multi-core era, writing a multi-threaded application always feels easier and more practical than buying a large number of multi-core hardware!

2. What is Java multi-thread programming?

The Java language itself is multi-threaded, So it provides our developers with language-level multi-threaded support, which is much more convenient than multithreading in C/C ++, at the same time, Java provides us with a lot of convenient conditions, making it much easier for us to develop multi-threaded applications. However, this is also relatively easy to develop a truly multi-threaded application, because there are too many problems to consider, visible and invisible. Therefore, we must lay a solid foundation in theory, then do a lot of exercises, truly understand the multi-threaded mechanism, and continue to practice in order to write beautiful concurrent applications.

3. What problems can be solved using multi-thread development?

In Java, multiple threads are used for implementation in many places, even though sometimes you have not found it, such as swing and SWT development. When we click a button, we can't always wait for the data processing in the background to jump to it, so that the user experience is too bad. We can complete the jump first, add other services that can be waited by the user (such as the buffer bar) and then present the results. Another example is the servlet that we must use when developing the Web. It is inherently multi-threaded, because for websites, multiple accesses at the same time are the minimum requirement, it is absolutely impossible for us to process requests one by one, which is totally unrealistic. In these cases, multithreading is used to concurrently process multiple requests, improving the response speed of the program.

4. Advantages and Disadvantages of multithreaded programming

Having said so much may bring you the impression that multithreading will always make the program run faster, so we should use it more. In fact, everything has two sides, and multithreading will bring some negative things, such as the perfect solution to the thread security caused by concurrency (this problem is not easy to solve and is also the most tricky thing to deal with multithreading, in addition, synchronization will be used to solve the current security problem, and synchronization will lead to a performance reduction). Therefore, considering the development difficulty, hardware requirements, maintenance costs, and other aspects, we still have to decide based on the actual situation. It is a matter of discussion whether multithreading is required or what part of the need is required.

5. Relationship between processes and threads

This is a classic question. Countless Interviewers Want to get your understanding of the thread and process from this question. It is a bit difficult to fully understand it, and it also takes time. From the perspective of program development, processes are the basic unit of resource allocation and the basic unit of a program or service. We can say that a process is the execution process of a program. This process includes many things, such as CPU execution time, running memory, and data. It is also a dynamic process. Threads are lightweight processes. They are resources shared by the parent process. Each thread executes an activity in an independent order in the parent process environment, each CPU core can only execute one thread at a time. Although we sometimes feel that our computer is running multiple tasks at the same time, every execution of them is stopped and stopped, the CPU allocates time to each process and thread in turn. Summarize the relationship between the two:

A>. A thread can belong to only one process, and a process can have multiple threads, but at least one thread. A thread is the minimum execution and scheduling unit that can be identified by the operating system.
B>. Resources are allocated to the process. All threads of the same process share all the resources of the process. Multiple threads in the same process share code segments (codes and constants), data segments (global variables and static variables), and extended segments (Heap Storage ). However, each thread has its own stack segment, which is also called the runtime segment, used to store all local variables and temporary variables.
C> the processor is allocated to the thread, that is, the thread that actually runs on the processing machine.
D>. Collaborate and synchronize threads during execution. Message Communication is required between threads of different processes for synchronization.

For a more detailed explanation, please read the relevant books on operating system principles for a deeper understanding of TX. This is not an important point here!

Ii. Simple example of multi-thread Development

In fact, programs are often the embodiment of real life. No program model cannot find a prototype in life, because programs are used to solve life problems. For example, if you are a regular person, you need to do the following things to get up every day: Get up, dress, wash, boil, or make tea) -- eat breakfast -- read newspapers and so on. If you want to complete these tasks in sequence, you need to do it one by one. You can do it without any problems. However, let's look at the water burning process. If we regard people as CPUs, the CPU is idle during the water burning process and the waiting conditions are met (the water is burned out ), we seem to be able to improve this process and do something else while burning water! Asynchronous operations are introduced here. We can do other things, such as washing and reading newspapers, while waiting for the water to be burned out. In this way, we save a lot of time to complete all the things that need to be done! This is a multi-threaded model: When the CPU is running and waiting for other operations such as Io, you can continue to do other things!

III. Basic methods for implementing multithreading in Java

There are two basic implementation methods for multithreading: Inheriting the Thread class and implementing the runnable interface. Here we will give a brief introduction, and we will go deeper in the subsequent articles. The content of the runnable interface is very simple, and there is only one abstract method: public abstract void run (); and The Thread class also implements the runnable interface. If you want to use this method to implement the runnable interface, it must be implemented using thread. But why is it designed like this? We know that Java has no multi-inheritance, so if we inherit the Thread class to implement multi-threading, that class cannot inherit other classes, which is obviously inconvenient in some cases, therefore, we can use the runnable interface.

1. Implement the runnable interface

public class MyThread implements Runnable{@Overridepublic void run() {for(int i=0; i<20; i++){System.out.println(Thread.currentThread().getName()+"-"+i);}}public static void main(String[] args) {Thread t1 = new Thread(new MyThread());Thread t2 = new Thread(new MyThread());t1.start();t2.start();}}

2. inherit the Thread class

public class MyThread extends Thread{@Overridepublic void run() {for(int i=0; i<20; i++){System.out.println(Thread.currentThread().getName()+"-"+i);}}public static void main(String[] args) {new MyThread().start();new MyThread().start();}}

Here we only provide the simplest and most primitive method, and will continue to increase the difficulty and knowledge points for expansion in the future.

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.