Analyze Java multi-threading mechanism

xiaoxiao2021-03-13  201

Process and application Difference process (Process) is the concept of initially defined in multi-user, multi-task operating system environments for representing the application of basic execution units in the memory environment. Take the UNIX operating system as an example, the process is the basic component in the UNIX operating system environment, which is the basic unit of system resource allocation. Almost all user management and resource allocation completed in the UNIX operating system are implemented by operating the operating system to control the application process. C, C , Java, etc. Source creations in Java are compiled into executable files with the corresponding compiler, submitted to the computer processor. At this time, the application in the executable state is called the process. From a user point of view, the process is an execution process for the application. From a core perspective of the operating system, the process represents the basic unit of the memory, CPU timefinder, etc., is a running environment provided by the running program. The difference between the process and the application is that the application is stored as a static file in a storage space such as a computer system, and the process is a system resource management entity maintained by operating system under dynamic conditions. The main features of the application process in a multi-task environment include: ● Process has an initial entry point of the memory cell during execution, and the process survival process always has independent memory address space; ● The survival status of the process includes creation, ready, Operating, blocking, and death; ● Different from the application process in the execution process to the CPU, the state of the process can be divided into user state and core state. The process in the user state is executed is the application instruction, and the application process in the core state is executed is the operating system instruction. During the startup process of UNIX operating system, the system automatically creates Swapper, INIT and other system processes, used to manage memory resources and scheduling user processes. In the UNIX environment, both the process created by the operating system is also created by the application, all have unique process ID (PID). The process of the process and the Java thread presents an initial entry point address of a memory space during the execution process, and the code execution sequence during execution process and the memory outlet point address used to identify the end of the process, each of the process execution One time has a unique processor instruction corresponding to the memory cell address. Threads defined in the Java language also include a memory entry point address, an exit point address, and a code sequence capable of sequential execution. However, the important difference between the process and thread is that the thread cannot be performed separately, which must be run in an active application process, so that the thread can be defined as the order of concurrency in the program. UNIX operating systems and Microsoft Windows operating systems support multi-user, multi-process concurrent execution, while Java language supports multiple implementation threads within the application process. Multi-threaded sense is that multiple logical units of an application can be executed concurrently. However, multithreading does not mean that multiple user processes are executed, and the operating system does not assign each thread as a stand-alone process to allocate independent system resources. The process can create their sub-process, the child process with the parent process has a different executable code and data memory space. The data memory space is shared in multiple threads in the process that represents the application, but keeps each thread have independent execution stacks and programs to perform contexts (context). Based on the above difference, threads may also be referred to as lightweight process (LWP). Mission collaboration and data exchange between different threads make it very cheap in computer system resource consumption. Threading requires the support of the operating system, not all types of computers support multithreaded applications. The Java programming language combines thread support with language operational environments, providing multitasking and execution capabilities. This is like a person in the process of dealing with housework, putting the clothes in the washing machine, then put rice in the rice cooker, then start cooking. It's okay, and the clothes are also washed at the same time.

It should be noted that the use of multi-threads in the application does not increase the data processing capability of the CPU. Only after multi-CPU's computer or under the network computing architecture, the Java program is divided into multiple concurrent execution threads, while starting multiple threads, so that different threads run in a Java virtual machine based on different processors. Improve the effectiveness of the application. In addition, the multi-threaded application is very advantageous if the application must wait for a relatively slow resource with a relatively slower data such as a network connection or database connection. The Internet-based application is necessary to multi-thread type, for example, when developing a server-side application to support a large number of clients, you can create a multi-threaded form to respond to the client's connection request, so that each connection user Exclusive a client connection thread. In this way, the user feels that the server is only serving its own services, thereby shortening the client response time of the server. Multi-threaded programming methods for Java languages ​​are easy to implement multithreaded applications using Java languages. Based on the multi-threaded application inherits or implements the object, two methods can be adopted: one is the application's concurrent operation object directly inherits the Java thread thread; another method is to define and send an object to implement the Runnable interface. Inheriting the multithreaded programming method of the Thread class The THREAD class is a class defined in the JDK to control the thread objects, encapsulated in this class. Method for performing thread control. See the following sample code: //Consumer.java import java.util *; class Consumer extends Thread {int nTime; String strConsumer; public Consumer (int nTime, String strConsumer) {this.nTime = nTime; this.strConsumer = strConsumer. Public void Run () {while {Try {system.out.println ("Consumer Name:" strconsuMer "); thread.sleep (ntime);} catch (Exception E) {E.PrintStackTrace );}}} Static public void main (String args []) {consumer aconsumer = new consumer (1000, "aconsumer"); aconsumer.start (); consumer bconsumer = new consumer (2000, "bconsumer"); bconsumer. start (); consumer cconsumer = new consumer (3000, "cconsumer"); cconsumer.start ();}} From the above program code: Multithreading execution underground consumer in inheriting the thread THREAD in the Java language and in main The instance of three consumer objects is created in the method. When calling the START method of the object instance, the RUN method defined in the Consumeer class is automatically called to start the object thread operation. The result of thread run is the content of the string member variable Strconsumer in the object instance every NTIME time. The multi-threaded programming method that inherits the Thread class is to enable the application class to inherit the Thread class and implement the concurrent processing process in the RUN method of the class.

Implementing another multithreaded program provided by the multithreaded program of the Runnable interface is another way to implement multithreaded applications in the Java language is multithreaded objects to implement RunNable interfaces and define RUN methods for starting threads in this class. The advantage of this definition is that multi-threaded application objects can inherit other objects rather than to inherit the Thread class, enabling the logic of class definitions. The multi-threaded application framework code for implementing the runnable interface is shown below: //Consumer.java import java.util. *; Class Consumer Implements Runnable {... ... public consumer (int NTIME, STRING STRCONSUMER) {... ...} public void Run ) {... ...} static public void main (string args []) {thread aconsumer = new thread (New Consumer (1000, "aconsumer")); aconsumer.Start (); // Other object instance running thread // ... ...}} From the above code, it can be seen that the class implements the RunNable interface and defines the RUN method in this class. This multi-threaded application implements an important difference between multi-threaded applications that inherited the Thread class in the method of starting multithreaded objects. In the above code, by creating a Thread object instance and applies an object as a parameter that creates a Thread class instance. Synchronous Java applications between threads share data resources for the same process, and multiple user threads may access sensitivity during concurrent operation. Define the concept of thread synchronization in Java to implement consistent maintenance of shared resources. Next, the thread interval synchronous control method is mainly developed by the author's recent mobile communication billing system, indicating the implementation process of multi-threaded synchronization mode in the Java language. Customer account class definition framework code without multi-threaded synchronous control policy is as follows: Public class registerAccount {float fbalance; // Customer Payment Method Public Void Deposit (FBALANCE = FFEES;} // Callometer Method Public Void Withdraw (FBalance - = FFEES;} ...} The reader may think that the above program code is fully able to meet the actual needs of the billing system. Indeed, the program is indeed reliable in a single-threaded environment. However, what is the situation of multi-process concurrency operation? Assuming this happens: The customer is using mobile communication device only by the customer service center, and the billing system starts the billing process at the end of the customer call, while the service center staff also submits the payment process. Readers can see that if this happens, the processing of the customer account is not serious. How to solve this problem? Very simple, in the RegisterAccount class method definition plus keywords synchronized. Thus, the shared resource involved in the method during the execution of the synchronization method (FBALANCE member variable in the code) will be plus shared lock to ensure that only the method can access the shared resource during the method operation until the method The thread runs opens the shared lock, and other threads can access these shared resources. The thread of the other access shared resource at the shared lock is not open at the blocking state.

RegisterAccount thread synchronization policy class definitions as shown in the following control code: public class RegisterAccount {float fBalance; public synchronized void deposit (float fFees) {fBalance = fFees;} public synchronized void withdraw (float fFees) {fBalance - = Ffees;} ... ...} From the code form defined by the thread synchronization mechanism, it can be seen that the method of accessing the Properties Keyword (PUBLIC) accessed by the shared resource, which is synchronized, so that the synchronization method is a shared resource When accessing, add a shared lock to these sensitive resources to control the resource exclusiveity during execution, and implement consistent management and maintenance of application system data resources. Free registration User Login Help Center Matrix Home Matrix Dynamic Technology Column Resource Download Wonderful Recommended Website Message User Center Matrix Forum Today is: Wednesday, July 16, 2003 You are now in: Home → Technology Columns → Java Core Technology (Java Basic Technology) JAVA Tutorial: Analysis of the multi-thread mechanism of Java (5) 2003-6-7 Matrix allows you to make progress browsing options: Color default grayscale olive green blue brown red This article has been viewed 31 Java threads management thread state control Here is that it is necessary to define the RUN method used to complete the actual function in this class, whether using inherited Thread class or the Runnable interface to implement the multi-threading capability of the application, this RUN method is called a thread body (Thread Body) ). Following the state in the computer system memory, threads can be classified into types created, ready, run, sleep, hang and death. These thread state types The thread is characterized: Create a status: After using the new keyword to create a thread object instance, it exists as an object instance, JVM does not have a thread to run a resource such as a CPU time piece; ready state: in place: Calling the start method in the thread of the creating state converts the state of the thread to the ready state. At this time, the thread has obtained other system resources other than the CPU time, and only the JVM thread scheduler is scheduled to the thread according to the thread, so that the thread has an opportunity to obtain the CPU time slice. Sleep Status: You can call the Sleep method during the thread run and specify the sleep time of the thread in the method parameter to convert the thread state to a sleep state. At this time, the thread stops running the specified sleep time without releasing the resource. After the time arrives, the thread is rescheduled and managed by the JVM thread scheduler. Suspend status: You can convert the state of the thread to a suspend state by calling the Suspend method. At this time, the thread will release all the resources occupied, and the JVM schedule forwards into the temporary storage until the application calls the Resume method to recover the thread operation. Death Status: The thread will terminate the run by the STOP method that runs or calls the thread object, and the resource occupied by the JVM is retracted by the JVM. The corresponding method is defined in the Java thread class to control and manage the thread state in the application. The meaning of the scheduling thread call call is that the JVM responds to a plurality of threads to run system-level to avoid multiple threads to compete for limited resources, resulting in a crash or crash. For threads to distinguish between the importantity of the operating system and the user, Java defines the priority policy of the thread.

Java divides the priority of the thread into 10 levels, respectively, with 1-10 numbers. The larger the number, the higher the level of the thread. Accordingly, in the Thread class define a member variable of the thread, the highest and ordinary priority, MIN_PRIORITY, MAX_PRIORITY, and NORMAL_PRIORITY, representing the priority levels of 1, 10 and 5, respectively. When a thread object is created, its default thread priority is 5. In order to control the running policy of the thread, Java defines all threads that are in the ready state in the system. The thread scheduler determines the thread into the processor to run according to the priority of the thread. Under the condition of multiple threads, the thread with high priority is performed before the low priority thread. The thread scheduler also uses the "preemptive" policy to schedule the thread execution, that is, the thread in which the current thread is executed in the ready state, the high priority thread is immediately scheduled. All threads with the same priority use rotation to share the CPU time slice. The method of setting up thread priority in the application is simple. After creating a thread object, you can call the SETPRIORITY method of the thread object to change the running priority of the thread, and you can also call the GetPriority method to get the priority of the current thread. A particular thread in Java is a low-level thread called a daemon thread. This thread has the lowest priority for serving other objects and threads in the system. The way a user thread is set to the daemon is the setDaemon method that calls the thread object before the thread object is created. Typical Guard WONES CONTERS is the system resource automatic reclaim thread in JVM, which is always run in a low-level state, used in real-time monitoring and management systems. Thread packet management Java defines a threadgroup object in a multi-threaded running system that implements centralized packet management of threads in accordance with specific functions. Each thread created by the user belongs to a thread group, which can be specified when the thread is created, or may not specify a thread group to make the thread among the default thread groups. However, once the thread adds a thread group, the thread has always exists in the thread group until thread death, and cannot change the thread group to which the thread belongs will be changed. When Java's Application application is running, JVM creates a web group named Main. Unless specified separately, the threads created in the application belong to the main thread group. Other names of other names can be created in the main thread group and add other threads to the thread group, and so on, constitute the tree management and inheritance relationship between threads and thread groups. Similar to threads, the scheduling, state management, and priority settings of thread groups can be performed for thread group objects. During the management process of the thread group, all threads joined to a thread group are viewed as a unified object. Summary: This article analyzes and explains the nature of the thread in the Java platform and the multi-threaded strategy of the application. Unlike other operating system environments, threads in the Java operating environment are similar to the process of multi-user, multi-task operating system environment, but in terms of process and thread operation and creation, the process has a significant difference from Java threads. In a UNIX operating system environment, the application can use the Fork function to create a child process, but the child process has a separate address space, system resource, and code execution unit, and the scheduling of the process is completed by the operating system, making Communication and thread coordination between application processes are relatively complicated. The multi-thread in the Java application is a plurality of parallel code executives that share the same application system resource, and the communication and coordination methods between threads are relatively simple. It can be said that the Java language supports the support of the application multi-threading capacity, Java as the advantage of the network programming language, laying a solid foundation for the realization of multiple clients in distributed applications, and enhances the response efficiency of the server.

转载请注明原文地址:https://www.9cbs.com/read-128978.html

New Post(0)