Java Thread: Uncover the real veil that the Run method is called

Source: Internet
Author: User

Lead

We know that new a thread, called its Start method, can create a thread, start the thread, and then execute the business logic that the thread needs to execute.

So how is the Run method executed?

Java thread and OS thread OS thread

We know that a thread in Java is actually a thread that corresponds to the operating system;

There are three ways in which the operating system implements threads:

    • Kernel thread Implementation
    • User Thread Implementation
    • User line loads lightweight process hybrid implementation

Detailed implementation is not specific, see «Deep Understanding Java Virtual Machine» Second Edition 12th Java memory model and thread (378 pages)

Java Threads

Java threads are implemented based on the user thread prior to JDK1.2. In JDK1.2, the threading model is replaced by the native threading model based on the operating system.

In the current JDK version, the operating system supports the threading model, which largely determines how the threads of a Java virtual machine are mapped, which cannot be agreed on different platforms.

For Sun JDK, both the Windows version and the Linux version are implemented using one-to-one threading model, and a Java thread is mapped to a lightweight process.

Above by personal understanding excerpt from: «In-depth understanding of Java Virtual Machines» Second Edition

How Java thread creation is created

Desc: We see that in either way we end up rewriting a method called run to handle our business logic, but we all call a Start method to start a thread;

What is the relationship between the Start method and the Run method? From the back of the introduction we will get a message: Run is a callback function, and our normal function is no different.

Implementation of Java Threads

The creation of a Java thread essentially corresponds to the creation of a local thread (native thread), which corresponds to one by one.

The key problem is that the local thread should be doing local code, and the Java thread-provided thread function (run) is a Java method that compiles Java bytecode.

So, Java threads actually provide a unified threading function that invokes Java threading methods through a Java virtual machine, which is implemented through a Java local method call.

The following is an example of the Thread#start method:

You 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 initiates the invocation of the native Start0 method, and the registration of these native methods is done at the time the thread object is initialized, look:

The thread class has a registernatives local method, and the main function of this method is to register some local methods for use by the thread class, such as Start0 (), Stop0 (), and so on, so to speak, all local methods that operate the local thread are registered by it.

This method is placed in a static statement block, which is called when the class is loaded into the JVM, and the corresponding local method is registered.

The local method, registernatives, is defined in the Thread.c file. THREAD.C is a very small file that defines common data and operations on threads that are used by each operating system platform as follows:

1JniexportvoidJnicall2Java_java_lang_thread_registernatives (jnienv *env, Jclass CLS) {//registernatives3(*env)registernatives (env, CLS, Methods, Array_length (methods));4  }5  StaticJninativemethod methods[] = {6{"start0","() V",(void*) &jvm_startthread},//Start0 Method7{"stop0","("Obj") V", (void*) &Jvm_stopthread},8{"isAlive","() Z",(void*) &jvm_isthreadalive},9{"suspend0","() V",(void*) &Jvm_suspendthread},Ten{"RESUME0","() V",(void*) &Jvm_resumethread}, One{"setPriority0","(I) V",(void*) &jvm_setthreadpriority}, A{"yield","() V",(void*) &Jvm_yield}, -{"Sleep","(J) V",(void*) &Jvm_sleep}, -{"CurrentThread","()"THD, (void*) &Jvm_currentthread}, the{"Countstackframes","() I",(void*) &Jvm_countstackframes}, -{"interrupt0","() V",(void*) &Jvm_interrupt}, -{"isinterrupted","(z) z",(void*) &jvm_isinterrupted}, -{"Holdslock","("Obj") Z",(void*) &Jvm_holdslock}, +{"getthreads","()["THD, (void*) &Jvm_getallthreads}, -{"dumpthreads","(["Thd")[["STE, (void*) &Jvm_dumpthreads}, +};

Observation of a small piece of code, you can easily see the Java thread call start->start0 method, actually call to the Jvm_startthread method, then how to deal with this method?

In fact, what we need to see is that the method eventually calls the Java thread's Run method, which is true.

In Jvm.cpp, there is the following code snippet:

Jvm_entry (void, Jvm_startthread (jnienv* env, Jobject jthread)) {    ... New Javathread (&thread_entry, SZ);    ...}

hereJvm_entry is a macro that is used to defineJvm_startthread function, you can see that the function creates a real platform-related local thread whose thread function is Thread_entry, as follows:
Static void thread_entry (javathread* thread, TRAPS) {    Handlemark HM (thread);    Handle obj (thread, thread,threadobj ());    Javavalue result (t_void);    Javacalls::call_virtual (&result,obj,    klasshandle (Thread,systemdictionary::thread_klass ()),    vmsymbolhandles::run_method_name (),     // look!, look at this .     vmsymbolhandles::void_method_signature (), THREAD);}

You can see that the Vmsymbolhandles::run_method_name method is called, and run_method_name is defined in VMSYMBOLS.HPP with a macro:

class vmsymbolhandles:allstatic {   ...    Template (Run_method_name,"run")  //look!!! Here is the decision to call the method name is "Run"!    ...}
Java Threads Create call relationships

Java Thread: Uncover the real veil that the Run method is called

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.