头图

: How to Create Multithreading" article, we have intuitively understood how 160ae34cc4d25d creates a thread in Java through Thread and Runnable. I believe you already have a certain sense of body. In this article, we will make some necessary explanations of threads based on the previous sample code to help you understand threads from a more basic level and lay a foundation for subsequent learning.

One, from the process to recognize the thread

Before the mid-1980s of the last century, the process has always been the basic unit have the resources and independently run However, with the development of computers, people have higher and higher requirements for the throughput of the operating system, and multi-processors have gradually developed. As the basic scheduling unit, the process has become more and more outdated because it is too heavy.

Think about it, when we create processes, we need to create PCBs for them and allocate all the resources we need, such as memory space, I/O devices, and so on. However, when the process is switched, the system also needs to retain the CPU environment of the current process and set a new process CPU environment, which takes time. That is to say, in the process, the system will spend a huge time and space overhead . In this way, in an operating system, too many processes cannot be set, and frequent switching cannot be performed. Obviously, this does not meet the development needs of the times.

Therefore, the process switches the huge overhead and multi-core CPU development, threads will follow the trend.

Conceptually, a thread can be understood as which is a basic unit that runs independently in the operating system. A process can have multiple threads . Moreover, has many similar attributes to the process compared to the process, so the thread is sometimes called the Light-Weight Process .

threads are relatively lightweight

Before threads, the system needs to switch processes when switching tasks, and the overhead is huge. However, after the thread is introduced, the thread belongs to the process, and the process is still the resource owner, and the thread only occupies a small amount of . At the same time, thread switching does not lead to process switching, so the overhead is small. In addition, processes and threads can be executed concurrently, so the operating system has obtained better concurrency, and can effectively improve the utilization of system resources and system throughput.

Two, Thread class-thread foundation in Java

In the first part of this article, we know the thread operating system 160ae34cc4d3e8 level. In Java, we need to Thread class, including some of its basic properties and basic methods. Thread is the foundation of Java multithreading. Please don't ignore this part because of its simplicity.

The following picture summarizes the core properties and methods of the Thread class:

1. How to construct a thread in Thread

There are 9 public constructors in Thread. Of course, we don't need to master all of them, but we can be familiar with a few of the more commonly used ones:

  • Thread() , this constructor will generate a name of Thread- + n n is an integer number generated by the internal method nextThreadNum()
  • Thread(String name) , it is a good practice to specify the thread name when constructing the thread;
  • Thread(Runnable target) , the incoming Runnable , which we have shown in the previous article;
  • Thread(Runnable target, String name) , specify the thread name when passing in the Runnable

2. Key attributes in Thread

understand the structure of Thread from the init()

Although Thread has 9 constructors, they are ultimately constructed by the following init() method, so if you understand this method, you will understand the construction process of Thread.


    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     * @param inheritThreadLocals if {@code true}, inherit initial values for
     *            inheritable thread-locals from the constructing thread
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals)

init() method has dozens of lines of code, but in order to save space, we only post the method signature here, and you can read the specific method body content by yourself. In the signature of the method, there are several important parameters:

  • g : The thread group to which the thread belongs. A thread group is a set of threads with similar behavior;
  • target : an object instance that inherits Runnable
  • name : the name of the thread;

Several other parameters usually do not need to be customized, just keep the default. If you look at init() method body code, you can see init() for the following several attributes do initialization:

  • name : the name of the thread;
  • group : the thread group to which the thread belongs;
  • daemon : Whether it is a daemon process;
  • priority : the priority of the thread;
  • tid : ID of the thread;

About the name

Although Thread will generate a default thread name, but in order to facilitate the output of logs and troubleshooting, compare recommend to manually set the name when you create a thread, such as anQiLaPlayer thread name can be set to Thread-anQiLa .

About thread ID

Like the thread name, each thread has its own ID. If you don't specify one, Thread will be automatically generated. To be precise, the thread ID is obtained by accumulating the static variable threadSeqNumber threadSeqNumber()

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

About thread priority

When creating a new thread, the priority of the thread is the same as the priority of the current parent thread by default. Of course, we can also set it through the setPriority(int newPriority) method. However, there are two points to note when setting thread priority:

  • The priority setting of : We can specify the priority of thread scheduling by numbers, but the final execution scheduling order will be determined by the operating system, because the priority setting in Thread is not the same as all Operating system one-to-one correspondence;
  • thread group is higher than the thread priority : each thread will have a thread group, and the thread priority number we set cannot be higher than the priority of the thread group. If it is higher, the priority of the thread group will be used directly.

3. The key method in the thread

Several important methods in Thread, such as start() , join() , sleep() , yield() , interrupted() etc., we will explain the usage of these methods in the next article in conjunction with the state of the thread. should be noted that notify() , wait() etc. are not methods of the Thread class, they are methods of Object .

Three, multi-threaded application scenarios

Through the previous analysis, we have recognized threads from the operating system level and Java. So, what scenarios need to consider using multithreading?

In general, when you encounter the following two types of scenarios, you need to consider multi-threading:

1. Asynchronous

When the two independent logic units do not need to be completed synchronously, they can be processed asynchronously through multithreading.

For example, the user sends an email message after registering. Obviously, registers and send messages are two independent logical units. After registration is completed, we can start another thread to complete the message sending, thereby achieving logical decoupling and shortening the response time of the registration unit.

2. Concurrent
Computers nowadays are basically multi-core processors. When processing batch tasks, multithreading can be used to increase the processing speed.

For example, suppose the system needs to send messages to 1 million users. It is conceivable that if single-threaded processing can only be completed without knowing the year of the monkey. At this time, we can create multiple threads through the thread pool to greatly improve efficiency.

Note that for some students, you may not have been exposed to the application scenario of too many threads. However, please do not ignore multi-threaded applications because of the simple scenes at work or the low amount of data. Multi-threading is widely used in all kinds of middleware and Internet manufacturers around you.

Risk tips when applying multithreading

Although multi-threading has many benefits, it is still necessary to analyze objectively based on scenarios. Unreasonable use of multi-threading will increase the system's security risk and maintenance risk . Therefore, when using multi-threading, please make sure that the scenario is reasonable and is under your control of technical ability.

The above is the entire content of the text. Congratulations on getting another star!

The Master's Trial

  • Use different construction methods to write two threads and print out the key information of the threads;
  • Retrieve information and compare the differences between processes and threads in detail.

About the author

Follow the public [160ae34cc4dcb0 mediocre technology joke ] to get timely article updates. Record technical stories of ordinary people, share technical articles with quality (as much as possible), and occasionally talk about life and ideals. Don't sell anxiety, don't sell courses.


秦二爷
70 声望3 粉丝