Introduction to Java threads for Java multithreaded programming

  • 2020-04-01 02:50:44
  • OfStack

One, thread overview

A thread is the basic unit of execution in which a program runs. When the operating system (not including single-threaded operating systems, such as Microsoft's early DOS) executes a program, it creates a process in the system in which at least one thread (called the primary thread) must be created as the entry point for the program to run. Therefore, any program running in the operating system has at least one main thread.
Processes and threads are two essential running 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). There may be one or more threads in a process. Processes and processes do not share memory, meaning that processes in the system run in separate memory Spaces. Lines in a process can share the memory space allocated by the system to the process.
Threads can not only share the process's memory, but also have their own memory space, this memory space is also called thread stack, is allocated by the system when the thread is established, mainly used to store the data used inside the thread, such as the variables defined in the thread execution function.
Note: any thread that is created executes a function called the thread execution function. You can also think of this function as an entry point for a thread (similar to the main function in a program). No matter what language or technique is used to create the thread, this function must be executed (the function may behave differently, but there will always be one). The third argument to the CreateThread API function for creating threads in Windows is the pointer to the execution function.
After the operating system divides the process into multiple threads, these threads can execute concurrently under the management of the operating system, which greatly improves the running efficiency of the program. Although thread execution is macroscopically multiple threads executing at the same time, it is really just a smoke screen for the operating system. Because a CPU can execute only one instruction at a time, it is impossible to execute two tasks on a computer with one CPU. The operating system, in order to improve the running efficiency of the program, removes a thread when it is idle and lets other threads execute, which is called thread scheduling. The reason we have multiple threads executing at the same time is because the switching time between threads is very short and, in general, very frequent. Let's say we have threads A and B. At run time, maybe A executes for 1 millisecond, then B executes for 1 millisecond, then B executes for 1 millisecond, then A executes for 1 millisecond. Since the time of 1 millisecond is hard for the average person to perceive, it looks like A and B are executing at the same time, but actually A and B execute alternately.

Second, the thread brings us the benefit

Using threads properly can reduce development and maintenance costs and even improve the performance of complex applications. In GUI applications, for example, events are better handled through the asynchronous nature of threads; Multiple threads can be set up in an application server program to handle client requests. Threads can even simplify the implementation of a virtual machine, such as the Java virtual machine (JVM) 's garbage collector, which typically runs in one or more threads. Therefore, using threads will improve our application in the following five ways:

1. Make full use of CPU resources
Most computers in the world today have only one CPU. Therefore, it is particularly important to make full use of CPU resources. When executing a single-threaded program, the CPU may be idle because the program is blocked. This will result in a huge waste of computing resources. Using multiple threads in a program allows you to run other threads when one thread is asleep or blocked and the CPU is idle. This makes it hard for the CPU to idle. Therefore, the CPU resources are fully utilized.

2.     Simplified programming model
If the program only performs one task, simply write a single-threaded program and follow the steps to perform that task. But 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. Such as the display of a clock, minutes, seconds three hands. Using a single thread, you have to determine the rotation time and Angle of each of the three Pointers in a loop. If three threads are used separately to handle the display of the three Pointers, it is a separate task for each thread. This helps developers understand and maintain the program.

3.     Simplifies the handling of asynchronous events
The easiest thing to do when a server application is receiving different client connections is to set up one thread for each client connection. The listener thread is then still responsible for listening for requests from the client. If the application is handled by a single thread, when the listener thread receives a client request, it begins to read the data from the client. After reading the data, the read method is blocked. To handle multiple client requests in a single thread, you must use non-blocking Socket connections and asynchronous I/O. But using asynchronous I/O is more difficult and error-prone than using synchronous I/O. Therefore, using multithreading and synchronous I/O makes it easier to handle asynchronous events that resemble multiple requests.

4.     Make the GUI more efficient
When using a single thread to process GUI events, a loop must be used to scan for GUI events that may occur at any time. If the code is too long, GUI events are "frozen" until the code is executed.
In modern GUI frameworks such as SWING, AWT, and SWT, a separate event dispatch thread (EDT) is used to scan GUI events. When we press a button, the button's click event function is called in the event dispatch thread. Because the task of the EDT is simply to scan GUI events, this way of responding to events is very fast.

5.     Cost savings
There are generally three ways to improve the execution efficiency of programs:
(1) increase the number of CPU of the computer.
(2) start multiple processes for a program
(3) use multiple processes in a program.
The first method is the easiest to do, but also the most expensive. This method does not require program modification, and in theory any program can use this method to improve execution efficiency. The second method does not require the purchase of new hardware, but it is not easy to share data in this way, which is inconvenient if the task to be completed by the program requires the sharing of data, and it consumes a lot of system resources to start multiple threads. The third method makes up for the shortcomings of the first and inherits their advantages. That is to say, don't need to purchase a CPU, also won't because rev. Too many threads and takes up a lot of system resources (by default, a thread of the memory space is much smaller than a process of memory space is much more), and multiple threads can simulate many CPU operation mode, therefore, using multithreading is the cheapest way to improve the efficiency of program execution.

Third, the Java thread model
Because Java is a pure object-oriented language, Java's threading model is also object-oriented. Java encapsulates all the necessary functionality of a Thread through the Thread class. To create a Thread, you must have a Thread execution function that corresponds to the Thread class's run method. The Thread class also has a start method, which is responsible for creating threads, equivalent to calling the Windows CreateThread function CreateThread. When the start method is called, the run method of the Thread class is automatically called if the Thread is successfully established. Therefore, any Java class that inherits a Thread can establish a Thread through the start method of the Thread class. If you want to run your own thread-execution function, override the Thread class's run method.
In addition to the Thread class, there is a Runnable interface in the Java Thread model that identifies whether a Java class can be used as a Thread class. This interface has only one abstract method, run, which is the Thread execution function of the Java Thread model. Therefore, the only criterion for a thread class is whether the class implements the run method of the Runnable interface; that is, a class that has a thread execution function is a thread class.
As you can see from the above, there are two ways to create threads in Java. One is to inherit the Thread class, and the other is to implement the Runnable interface and create threads through the Thread and the class that implements Runnable. But their district is through inheritance Thread class to create threads, although in achieving more easy, but because Java does not support multiple inheritance, therefore, the Thread class if inherited Thread, can no longer carry on other classes, therefore, provided by Java Thread model implements the Runnable interface method to establish the threads, this Thread class can inherit and when necessary business related classes, rather than the Thread class.


Related articles: