Java multithreading beginner's Guide (1): thread Introduction

Source: Internet
Author: User


Blogjava

I. Thread Overview

A thread is the basic execution unit of a program. When an operating system (excluding a single-threaded operating system, such as Microsoft's earlier DOS) executes a program, a process is created in the system. In this process, at least one thread (called the main thread) must be created to serve as the entry point for the program running. Therefore, any program running in the operating system has at least one main thread.

Processes and threads are two essential operating models in modern operating systems. There can be multiple processes in the operating system, including system processes (processes established within the operating system) and user processes (processes established by user programs ); A process can have one or more threads. No memory is shared between processes. That is to say, the processes in the system run in their independent memory space. A thread in a process can share the memory space allocated to the process by the system.

A thread not only shares the memory of a process, but also has its own memory space. This memory space is also called a thread stack, which is allocated by the system when a thread is created, it is mainly used to save the data used inside the thread, such as the variables defined in the thread execution function.

Note: any thread will execute a function when it is created. This function is called a thread execution function. You can also regard this function as the thread entry point (similar to the main function in the program ). No matter what language or technology is used to create a thread, you must execute this function (This function may be in different forms, but there will be such a function ). For example, in Windows, the third parameter of CreateThread, the API function used to create a thread, is the pointer to the execution function.

After the operating system divides the process into multiple threads, these threads can be executed concurrently under the management of the operating system, which greatly improves the program running efficiency. Although the execution of a thread is performed by multiple threads at the same time in a macro view, it is only a blind view of the operating system. Since one CPU can only execute one command at a time, it is impossible to execute two tasks simultaneously on a computer with one CPU. In order to improve the program running efficiency, the operating system will remove this thread when a thread is idle and allow other threads to execute it. This method is called thread scheduling. On the surface, the reason why we execute multiple threads at the same time is that the switching time between different threads is very short, and the switching is usually very frequent. Suppose we have threads A and B. During running, it may be that after A is executed for 1 millisecond, B is executed for 1 millisecond after switching to B, and then switched to A, and A is executed for 1 millisecond. Since 1 ms is hard for ordinary people to perceive, it looks like A and B are executed at the same time, but in fact A and B are executed alternately.

Ii. Benefits of threads

Reasonable Use of threads can reduce development and maintenance costs and even improve the performance of complex applications. For example, in GUI applications, events are better handled by asynchronous threads. In application server programs, multiple threads can be created to process client requests. Threads can even simplify the implementation of virtual machines. For example, garbage collector of Java virtual machines (JVM) usually run in one or more threads. Therefore, using threads will improve our applications in the following five aspects:

1. Make full use of CPU resources

Most computers in the world now have only one CPU. Therefore, it is particularly important to make full use of CPU resources. When a single-threaded program is executed, the CPU may be idle due to program congestion. This will cause a lot of waste of computing resources. Multithreading can be used in a program to run other threads when a thread is in sleep or blocked State while the CPU is in idle state. In this way, it is difficult for the CPU to be idle. Therefore, the CPU resources are fully utilized.

2. Simplified Programming Model

If the program completes only one task, you only need to write a single-threaded program and write code according to the steps for executing the task. However, to complete multiple tasks, if you still use a single thread, You have to determine in the program whether each task should be executed and when to execute it. For example, the hour, minute, and second of a clock are displayed. When using a single thread, You must judge the rotation time and angle of the three pointers one by one in the loop. If three threads are used to process the display of the three pointers separately, each thread is used to execute a separate task. This helps developers understand and maintain programs.

3. Simplified asynchronous event processing

When a server application receives different client connections, the simplest solution is to create a thread for each client connection. Then the listening thread is still responsible for listening for requests from the client. If such an application uses a single thread for processing, when the listening thread receives a client request, it starts to read the data sent from the client. After reading the data, the read method is blocked. That is to say, this thread will no longer be able to listen to client requests. To process multiple client requests in a single thread, you must use a non-blocking Socket connection and asynchronous I/O. However, asynchronous I/O is more difficult to control and error-prone than synchronous I/O. Therefore, using multithreading and synchronous I/O makes it easier to process asynchronous events similar to multiple requests.

4. Make the GUI more efficient

When using a single thread to handle GUI events, you must use a loop to scan GUI events that may occur at any time. In addition to scanning GUI events, you must also run other program code within the loop. If the code is too long, the GUI event will be frozen until the code is executed.

A separate event dispatch thread (EDT) is used in modern GUI frameworks (such as SWING, AWT, and SWT) to scan GUI events. When we press a button, the Click Event function of the button will be called in the event dispatch thread. Because EDT tasks only scan GUI events, this method reflects events very quickly.

5. Cost Saving

There are three methods to improve program execution efficiency:

(1) Increase the number of CPUs in the computer.

(2) Start Multiple processes for a program

(3) Use multiple processes in a program.

The first method is the easiest, but also the most expensive. This method does not need to be modified. Theoretically, any program can use this method to improve execution efficiency. The second method is not to purchase new hardware, but it is not easy to share data. If the task to be completed by this program needs to share data, this method is not convenient, in addition, starting multiple threads will consume a large amount of system resources. The third method makes up for the shortcomings of the first method, and inherits their advantages. That is to say, neither the purchase of CPU nor the occupation of a large amount of system resources due to too many threads (by default, the memory space occupied by a thread is much smaller than the memory space occupied by a process), and multithreading can simulate the running mode of multiple CPUs. Therefore, multithreading is the cheapest way to improve program execution efficiency.

Iii. Java thread model

Because Java is a pure object-oriented language, the Java thread model is also object-oriented. Java encapsulates all the functions required by the Thread through the Thread class. To create a Thread, you must have a Thread to execute the function. The Thread execution function corresponds to the run method of the Thread class. The Thread class also has a start method, which is used to create a Thread, which is equivalent to calling the CreateThread function of Windows. After the start method is called, if the Thread is successfully established and the run method of the Thread class is automatically called. Therefore, any Java class that inherits the Thread can use the start method of the Thread class to create a Thread. If you want to run your own Thread to execute a function, you must overwrite the run method of the Thread class.

In the Java Thread model, besides the Thread class, there is also a Runnable interface that identifies whether a Java class can be used as a Thread class. This interface has only one abstract method run, that is, the thread execution function of the Java thread model. Therefore, the only standard for a Thread class is whether the class implements the run method of the Runnable interface. That is to say, the class with the thread execution function is the Thread class.

We can see from the above that there are two ways to create a Thread in Java: one is to inherit the Thread class, and the other is to implement the Runnable interface, thread and Runnable class are used to create a Thread. In fact, these two methods are essentially one method, that is, the Thread class is used to create a Thread and run the run method. However, their main region is to establish threads by inheriting the Thread class. Although it is easier to implement, Java does not support multi-inheritance. Therefore, if this Thread class inherits the Thread class, therefore, the Java thread model provides a method to implement the Runnable interface to create a thread, in this way, the Thread class can inherit the business-related classes when necessary, rather than the Thread class.

 

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.