Chapter 16 A Preliminary Understanding of Java Threads

Preface

I often think about why some children are good at Chinese and not good at math? Some are good in mathematics and not good in Chinese? Are the two contradictory?
Languages ​​are often full of stories, vivid and rich. Mathematics is often full of logic and monotony, and repeated numbers may dazzle children who do not love math. Extending from this question, some people like to read stories and can stay up all night, but they often like to doze off while studying.
So I think if learning is boring, it will definitely make people feel boring. Programmers are an industry that requires continuous learning. What if you doze off when you encounter learning? Therefore, I have summed up some experiences and combined the learning of this matter with the story, so that learning will no longer feel very boring.
For example, for the subject of this research article, the Thread class, thread. If you just look at its source code, methods, and constructors, without actual business requirements, it may be boring. But if you learn threading in a story-like way of thinking, it might be much more interesting.

Origin of thread

At the very beginning, there were only processes and no threads. At the beginning of the development of computers, the program was static, and there was no specific expression of the running process of the program, so the process appeared. The process represents the running process of the program, so the process has a life cycle and different states.
Each process will be allocated a certain amount of memory, program control block and other resources. At the beginning of the allocation, it is a process of constructing a process, which is equivalent to the preparation of the program in the early stage. This process is called the initial state, and after the preparation is called the ready state, it means that the process is ready and waiting for the call of the CPU at any time. During the operation of the CPU, it is called the running state. However, in multi-program design, a process cannot occupy the CPU, and other processes must take turns to use it, so when the process exits the CPU after being interrupted by some event, it is called Waiting state. The waiting state cannot directly enter the running state. It must first enter the ready state before waiting for the call of the CPU. This process continues to loop until the process is completed, which is called the end state of the process.

Insert picture description here

I probably drew a basketball court to show it briefly. There are 5 people on the red team and 4 alternates on the basketball court, but there are only 6 basketball uniforms. So the running state of a team member should be like this.
1. First put on the team uniform and enter the ready state
2. Enter to play on the court and enter the running state
3. Turn off the court and enter the waiting state, but you have to take off the team uniform.
4. Loop until the end.
The difference is that in a computer, there are many processes, and they may all be in the ready state at the same time. This requires waiting for the CPU to call through the algorithm instead of the queue mode in the figure.
During the running of the program, it needs to be switched continuously. Because the process has a lot of resources, the cost of switching becomes high, and the process is also called a heavyweight process. In order to improve this situation, threads appeared.
A thread is a lightweight process. A process can have multiple threads. It reduces the overhead caused by process state switching and has the role of a process. In a process, all threads share the resources of the process. At the same time it also has all the states that the process has.

State of the thread

There are three common thread states: ready, running, and waiting.
In order to describe the integrity of the thread, two states, start and end, are added.
In the first computer, threads were running in memory, but the memory was often not enough, so the concept of virtual memory was added to the disk. When some programs are not needed or cannot be added to the memory, they will be put into the virtual memory. At this time, the program is in a suspended state, and the virtual memory is actually on the external memory. So the whole has become the following six types:

Initial, ready, running, waiting, suspending, ending

The state of the program in operation is divided into the above-mentioned about six kinds of fine-grained ones. So how to control the state of the thread, or perform some actions based on the state of the thread.
This is what the programmer has to do. Different languages ​​provide different control methods. For Java, Thread is an abstract definition of thread. Many methods are provided around different state transitions of threads. These methods may be to turn the ready state into the running state, such as the start() method.
There are many methods defined in the Thread object, which will be studied in the next chapter. Different methods will make the thread transition from which state to which state.

Multithreading

During the development of computers, the speed of the CPU has become faster, far exceeding the speed of other hardware. Although the design of the cache has improved the CPU usage rate, the CPU usage rate is still very low. Therefore, the computer tycoons thought of multi-program design, allowing different processes to use the CPU in turn, which not only increased the utilization rate of the CPU, but also allowed the computer to handle multiple process tasks at the same time, such as playing games and chatting.
The design of multi-programs makes the computer more efficient, but multi-programs also have disadvantages.
In real life, the number of threads is often far more than the number of cpu cores, so it is not possible to avoid the use of one core and multiple threads in turn. The CPU is divided into time slices, and each thread takes turns to obtain time slices, but this process is unstable. If a thread occupies a CPU, the time it takes to complete the operation is the fastest. The intervention of multiple threads makes the running time of a single thread longer, even if it is only a few milliseconds. If in some very demanding fields, such as missiles, aerospace, etc., these jet lags will be fatal.
Therefore, multi-threading improves the efficiency of the computer and at the same time increases the running time of a single thread.

So in a multi-threaded environment, how to make this instability relatively stable?
Thus, thread priority was born.

Thread priority Priority

In the concept of time slices, each thread's acquisition of time slices is unstable. In order for some important threads to execute the program faster, more time slices need to be acquired. Thread priority is to achieve a similar purpose.
In JAVA, there are a total of 10 thread priority levels, with high levels taking precedence over low levels. From level 1 to level 10, thread priority levels gradually increase. Level 10 is the highest priority. The initially created Thread thread object is set to level 5 by default. If each thread does not set the priority level separately, theoretically, they have the same probability of grabbing the time slice.
Although it is possible to set the priority of a thread, when there are more and more threads in the system, they will have the characteristics of clustering together and dividing people into groups, whether it is business connections or similar functions. In order to better manage these threads with certain characteristics, the concept of thread groups is proposed.

Thread group ThreadGroup

A thread group is a class that manages threads, or is understood as a thread manager of multiple threads. When there are more and more workers in the factory, the boss will no longer manage these workers one by one, but recruit personnel. Miss Personnel will manage these workers, including attendance, wages, leave and so on. The concept of thread group is also based on this concept, which is equivalent to Miss Personnel.
In JAVA, it provides many methods for the caller to uniformly operate these threads through Miss Personnel (thread group). For example, setting the priority of this group, interrupting all threads in this group, etc...
Each ThreadGroup manages some threads, and its specific structure and structure will be analyzed in detail later.

ThreadLocal

what is this? Why was it designed? What are the advantages and disadvantages? How to avoid shortcomings?
Although there are many same, similar or different answers on the Internet. In my understanding, the emergence of ThreadLocal only solves the problem of parameter passing, and cannot solve concurrent shared variables. Use ThreadLocal to pass public variables between different levels, similar to a session in the life cycle of a thread.

Thread Pool

Since the creation and destruction of threads will consume a certain amount of cpu, in certain business scenarios, such as frequent calls to create and destroy threads, the computer's cpu will be consumed in a large amount to affect the performance of the program. And in this business scenario, there is no need to do so. The concept of thread pool is based on the principle of thread reuse. After thread 1 is created by user A, user B immediately comes. At this time, thread 1 can continue to serve user B without being destroyed. If this concept is not adopted, then a user will create and destroy a thread, increasing the number of creation and destruction, thereby affecting the performance of the entire system.
The thread pool is based on the principle of multiplexing. The initial number of threads, the number of standby threads, the maximum number of threads, etc., and the destruction mechanism can be set according to different business scenarios.

to sum up

Follow-up will gradually analyze the principles, usage scenarios, tuning mechanisms, etc. of threads, thread groups, and thread pools.

Guess you like

Origin blog.csdn.net/weixin_43901067/article/details/105413648