Java Methods for creating threads

Source: Internet
Author: User
Tags thread class

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{
public void Run () {
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:

MyThread MyThread = new MyThread ();
Mythread.start ();
Implementing the Runnable Interface

Class Myrunnable implements runnable{
public void Run () {
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.

Thread myThread = new Thread (new myrunnable ());
Mythread.start ();
1
2
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:

Public synchronized void Start () {
...
Start0 ();
You can see that it actually calls the local method Start0, which declares the following:

Private native void Start0 ();
1
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.

private static native void Registernatives ();
static{
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

Jniexport void Jnicall
Java_java_lang_thread_registernatives (jnienv *env, Jclass CLS) {
(*env)->registernatives (env, CLS, Methods, Array_length (methods));
}
Static Jninativemethod 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 ") [[" Java Method 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{
public void Run () {
System.out.println ("My thread is started.");
}
}
1
2
3
4
5
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:

MyThread MyThread = new MyThread ();
Mythread.start ();
1
2
Implementing the Runnable Interface

Class Myrunnable implements runnable{
public void Run () {
System.out.println ("My runnable is invoked.");
}
}
1
2
3
4
5
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.

Thread myThread = new Thread (new myrunnable ());
Mythread.start ();
1
2
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:

Public synchronized void Start () {
...
Start0 ();
...
}
1
2
3
4
5
You can see that it actually calls the local method Start0, which declares the following:

Private native void Start0 ();
1
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.

private static native void Registernatives ();
static{
Registernatives ();
}
1
2
3
4
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

Jniexport void Jnicall
Java_java_lang_thread_registernatives (jnienv *env, Jclass CLS) {
(*env)->registernatives (env, CLS, Methods, Array_length (methods));
}
Static Jninativemethod 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},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
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))
...
Native_thread = new Javathread (&thread_entry, SZ);
...
1
2
3
4
* * 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

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 (),
Vmsymbolhandles::void_method_signature (), THREAD);
}
1
2
3
4
5
6
7
8
9
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 Diagram 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))
...
Native_thread = 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

static void Thread_entry (javathread* thread, TRAPS) {
Handlemark HM (THREAD);
Handle obj (THREAD, Thread->threadobj (www.feilinyule.cn));
Javavalue result (t_void);
Javacalls::call_virtual (&result,obj,
Klasshandle (Thread,systemdictionary::thread_klass ()),
Vmsymbolhandles::run_method_name (www.wangcai157.com),
Vmsymbolhandles::void_method_signature (www.yibaoyule1.com), 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

Java methods for creating threads

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.