Learn how the start method of a Java thread callbacks the Run method

Source: Internet
Author: User
Tags thread class

The interview may be asked why we execute the run () method when we call the start () method, why can't we call the Run () method directly?

Java Methods for creating threads

In fact, the most important thing to create a thread is to provide the thread function (the callback function), which acts as the entry function for the newly created thread, implementing its desired function. Java provides two ways to create a thread:

Inherit the Thread class

class MyThread extends Thread{     publicvoidrun() {            System.out.println("My thread is started.");     } }

Implement the Run method of the inheriting class, and then you can create the object of the subclass, and call the Start method to create a new thread:

new MyThread(); myThread.start();

Implementing the Runnable Interface

class MyRunnable implements Runnable{     publicvoidrun() {         System.out.println("My runnable is invoked.");     } }

An object of a class that implements the Runnable interface can be passed as a parameter to the created thread object, and the code in the Run method can be run in a new thread by calling the Thread#start method.

newnew MyRunnable()); myThread.start();

As you can see, no matter which method you use, you are actually implementing a run method. The method is essentially the previous callback method. The newly created thread by the Start method calls this method to execute the required code. As you can see from the back, the Run method is not a real thread function, just a Java method called by a thread function, and no other Java method is fundamentally different.

Implementation of Java Threads

Conceptually, the creation of a Java thread essentially corresponds to the creation of a local thread (native thread), which corresponds to one by one. The problem is that the local thread should be doing local code, and the Java thread provides a Java method that compiles Java bytecode, so it is conceivable that the Java thread actually provides a uniform thread function that invokes the Java threading method through a Java virtual machine. This is done through a Java local method call.

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

publicsynchronizedvoidstart() {     …    start0();     …}

You can see that it actually calls the local method Start0, which declares the following:

privatenativevoidstart0();

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 indicates that when the class is loaded into the JVM, it is called and the corresponding local method is registered.

privatestaticnativevoidregisterNativesstatic{   registerNatives(); }

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

Listing 1

JniexportvoidJnicall java_java_lang_thread_registernatives (jnienv *env, Jclass cls) {(*env)->registernatives (env, CLS, Methods, Array_length (methods)); }StaticJninativemethod methods[] = {{"Start0","() V",(void*) &jvm_startthread}, {"Stop0","("Obj") V ", (void*) &jvm_stopthread}, {"IsAlive","() Z",(void*) &jvm_isthreadalive}, {"Suspend0","() V",(void*) &jvm_suspendthread}, {"RESUME0","() V",(void*) &jvm_resumethread}, {"SetPriority0","(I) V",(void*) &jvm_setthreadpriority}, {"Yield","() V",(void*) &jvm_yield}, {"Sleep","(J) V",(void*) &jvm_sleep}, {"CurrentThread","()"THD, (void*) &jvm_currentthread}, {"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},};

In this way, it is easy to see how the Java thread calls start, and actually calls the Jvm_startthread method, which is the logic of this method. In fact, what we need is (or Java performance behavior) that the method eventually calls the Java thread's Run method, which is indeed the case. In Jvm.cpp, there is the following code snippet:

JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))    …    new JavaThread(&thread_entry, sz);    …

* * Here Jvm_entry is a macro, used to define the **jvm_startthread function, you can see that the function creates a real platform-related local thread whose thread function is Thread_entry, as shown in Listing 2.

Listing 2

staticvoid 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(), vmSymbolHandles::void_method_signature(),THREAD); }

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

class vmSymbolHandles: AllStatic {    …    template(run_method_name,"run")    …}

As to how run_method_name is defined, this article does not repeat itself because of the cumbersome code details involved. Interested readers can view the source code of the JVM themselves.

Figure. Java Thread Creation Call graph

Start () Create a new process
Run () No


Links: Processes and threads in Java

Learn how the start method of a Java thread callbacks the Run method

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.