Java and thread, Java thread
Introduction
We know that a new thread can call its start method to create a thread, start the thread, and then execute the business logic that the thread needs to execute,
How is the run method executed?
Java thread and OS thread
We know that a java thread actually corresponds to a thread in the operating system;
The operating system has three ways to implement threads:
- Kernel thread implementation
- User thread implementation
- Hybrid Implementation of user threads and lightweight Processes
Kernel thread implementation
Brief description:
The Kernel-Level Thread (KLT) is a Thread directly supported by the operating system Kernel. This Thread completes Thread switching by the Kernel, and the Kernel schedules the Thread through the Controller scheduler,
And maps tasks of threads to various processors.
Each kernel thread can be regarded as a separation of the kernel, so that the operating system can handle multiple tasks. This multi-threaded kernel is called a multi-threaded kernel;
Generally, programs do not directly operate on Kernel threads, but use an advanced interface of kernel threads: Light Weight Process (LWP). Lightweight processes are what we usually call
Thread. Each lightweight process is supported by a kernel thread. The relationship between a Lightweight Process and the kernel thread is called a one-to-one thread model.
Advantages: With the support of kernel threads, each lightweight process is called an independent scheduling unit. Even if a lightweight process is blocked in the system, the entire process will not be affected;
Disadvantage:
User thread implementation
Brief description:
User thread:
- Broadly speaking, any non-kernel Thread can be considered as a User Thread (UT );
- In a narrow sense, it is completely built on the thread library of the user space, and the system kernel cannot perceive the implementation of the thread;
Features:
The advantage of a user thread is that the system kernel support is not required, and the disadvantage is that there is no Kernel support. All thread operations (such as thread creation, switching, and scheduling) must be handled by the user program.
Hybrid Implementation of user threads and lightweight Processes
Brief description:
User thread + lightweight process features:
- User thread creation, analysis, switching, and other operations are cheap;
- Supports large-scale concurrent user threads;
- The lightweight process provided by the operating system serves as a bridge between the user thread and the kernel thread, providing Thread Scheduling and processor ing;
- System calls of user threads are completed through lightweight processes, reducing the risk that the entire process is completely blocked;
- The number of such user threads and lightweight processes is variable, that is, the relationship between N: M, called the multi-to-multi-thread model.
Java thread
Java threads were implemented based on user threads before JDK1.2. In JDK1.2, the thread model is replaced by the operating system native thread model.
In the current JDK version, the thread model supported by the operating system determines to a large extent how the threads of the Java Virtual Machine are mapped, this cannot be achieved on different platforms.
For Sun JDK, both Windows and Linux are implemented using a one-to-one thread model. A Java thread is mapped to a lightweight process.
Java thread Creation Method
Desc: we can see that no matter which method we create, we will eventually rewrite a method called run to process our business logic. However, we call a start method, to start a thread;
So what is the relationship between the start method and the run method? We will get the following information: run is a callback function, which is no different from our common functions.
Java thread implementation
The creation of a Java thread corresponds to the creation of a local thread.
The key issue is: the local thread should execute local code, while the thread function (run) provided by the Java thread is a Java method and the compiled Java bytecode,
Therefore, the Java thread actually provides a unified thread function, which calls the Java thread method through the Java Virtual Machine, which is implemented through the Java local method call.
The following is an example of the Thread # start method:
We can see that it actually calls the local method start0, And the start0 declaration is as follows:
private native void start0();
That is, the newly created Thread starts to call the native start0 method, and the registration of these native methods is completed at the Thread object initialization. look:
The Thread class has a registerNatives local method. The main function of this method is to register some local methods for the Thread class, such as start0 () and stop0 (). You can say that, all local methods that operate on the local thread are registered by it.
This method is placed in a static statement block. When the class is loaded into the JVM, it is called and the corresponding local method is registered.
The local method registerNatives is defined in the Thread. c file. Thread. c is a small file that defines the common data and operations on threads used by each operating system platform, as follows:
1 JNIEXPORT void JNICALL 2 values (JNIEnv * env, jclass cls) {// registerNatives 3 (* env)-> RegisterNatives (env, cls, methods, ARRAY_LENGTH (methods )); 4} 5 static JNINativeMethod methods [] = {6 {"start0", "() V", (void *) & JVM_StartThread}, // start0 Method 7 {"stop0 ", "(" OBJ ") V", (void *) & JVM_StopThread}, 8 {"isAlive", "() Z", (void *) & JVM_IsThreadAlive }, 9 {"suspend0", "() V", (void *) & JVM_SuspendThread}, 10 {"resume0", "() V", (void *) & JVM_ResumeThread }, 11 {"setPriority0", "(I) V", (void *) & JVM_SetThreadPriority}, 12 {"yield", "() V", (void *) & JVM_Yield}, 13 {"sleep", "(J) V", (void *) & JVM_Sleep}, 14 {"currentThread", "()" THD, (void *) & JVM_CurrentThread}, 15 {"countStackFrames", "() I", (void *) & JVM_CountStackFrames}, 16 {"interrupt0", "() V ", (void *) & JVM_Interrupt}, 17 {"isInterrupted", "(Z) Z", (void *) & JVM_IsInterrupted}, 18 {"holdsLock ", "(" OBJ ") Z", (void *) & JVM_HoldsLock}, 19 {"getThreads", "() [" THD, (void *) & JVM_GetAllThreads }, 20 {"dumpThreads", "([" THD ") [[" STE, (void *) & JVM_DumpThreads}, 21 };
Looking at the above code, we can easily see that the Java thread calls the start-> start0 method and actually calls the JVM_StartThread method. How does this method work?
In fact, we need to see that this method will eventually call the Java thread's run method. This is indeed the case.
The following code snippet is available in jvm. cpp:
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)){ ... native_thread = new JavaThread(&thread_entry, sz); ...}
HereJVM_ENTRY
Is a macro used to defineJVM_StartThread function. You can see that a real local platform-related thread is created in the function. The thread function is thread_entry, as shown below:
Static void thread_entry (JavaThread * thread, TRAPS) {HandleMark hm (THREAD); Handle obj (THREAD, thread-> threadObj (); JavaValue result (T_VOID); javacils :: call_virtual (& result, obj, KlassHandle (THREAD, SystemDictionary: Thread_klass (), vmSymbolHandles: run_method_name (), // LOOK! Check out vmSymbolHandles: void_method_signature (), THREAD );}
We can see that the vmSymbolHandles: run_method_name method is called, while run_method_name is defined by a macro in vmSymbols. hpp:
Class vmSymbolHandles: AllStatic {... template (run_method_name, "run") // LOOK !!! The name of the called method is "run "! ...}Java threads create call relationships