從 Hotspot 虛擬機角度來分析 Java 線程啟動
基本概念
Java 線程其實是映射到操作系統的內核線程上的,所以 Java 線程基本上也就是操作系統在進行管理。在 Linux系統中,線程和進程用的是同一個結構體進行描述的,只不過進程擁有自己獨立的地址空間,而同一個進程的多個線程之間是共享資源的。
簡單說明:本文基于 openjdk 1.8 進行
線程狀態
每種線程狀態的切換條件, 以及調用方法如下圖所示 :
線程具有以下幾種狀態 Java 的線程狀態在 Thread.State 枚舉中定義代碼如下
- public enum State {
- //新創建,未啟動
- NEW,
- //在jvm 中運行,也可能正在等待操作系統的其他資源
- RUNNABLE,
- //阻塞,并且正在等待監視器鎖
- BLOCKED,
- //處于等待狀態的線程,正在等待另一個線程執行特定的操作
- WAITING,
- //限期等待, 可以設置最大等待時間
- TIMED_WAITING,
- //結束
- TERMINATED;
- }
線程創建
繼承 Thread 類, 代碼如下:
- class PrimeThread extends Thread {
- long minPrime;
- PrimeThread(long minPrime) {
- this.minPrime = minPrime;
- }
- public void run() {
- // compute primes larger than minPrime
- . . .
- }
- }
- // 啟動線程
- PrimeThread p = new PrimeThread(143);
- p.start();
實現 Runable 接口, 代碼如下 (通常推薦使用這種方式):
- class PrimeRun implements Runnable {
- long minPrime;
- PrimeRun(long minPrime) {
- this.minPrime = minPrime;
- }
- public void run() {
- // compute primes larger than minPrime
- . . .
- }
- }
- // 啟動線程
- PrimeRun p = new PrimeRun(143);
- new Thread(p).start();
hotspot 源碼
JNI 機制
JNI 是 Java Native Interface 的縮寫,它提供了若干的 API 實現了Java和其他語言的通信(主要是C和C++)。
JNI的適用場景 當我們有一些舊的庫,已經使用C語言編寫好了,如果要移植到Java上來,非常浪費時間,而JNI可以支持Java程序與C語言編寫的庫進行交互,這樣就不必要進行移植了。或者是與硬件、操作系統進行交互、提高程序的性能等,都可以使用JNI。需要注意的一點是需要保證本地代碼能工作在任何Java虛擬機環境。
- JNI的副作用 一旦使用JNI,Java程序將丟失了Java平臺的兩個優點:
- 程序不再跨平臺,要想跨平臺,必須在不同的系統環境下程序編譯配置本地語言部分。
程序不再是絕對安全的,本地代碼的使用不當可能會導致整個程序崩潰。一個通用規則是,調用本地方法應該集中在少數的幾個類當中,這樣就降低了Java和其他語言之間的耦合。
舉個例子 這塊操作比較多,可以參考如下的資料
- https://www.runoob.com/w3cnote/jni-getting-started-tutorials.html
啟動流程
啟動流程如下
線程啟動
Java 創建線程 Thread 實例之后,是通過 start 方法進行啟動該線程,通知執行。在 start 方法的內部,調用的是 start0() 這個本地方法。我們可以從該方法為入口分析 JVM 對于 Thread 的底層實現。
- public synchronized void start() {
- // 判斷線程狀態
- if (threadStatus != 0)
- throw new IllegalThreadStateException();
- // 添加到組
- group.add(this);
- boolean started = false;
- try {
- // 啟動線程
- start0();
- started = true;
- } finally {
- try {
- if (!started) {
- group.threadStartFailed(this);
- }
- } catch (Throwable ignore) {
- /* do nothing. If start0 threw a Throwable then
- it will be passed up the call stack */
- }
- }
- }
- private native void start0();
start0() 是一個本地方法,咱們按照 JNI 規范可以到 hotspot 虛擬源碼中查找 java_lang_Thread_start0 這個函數。定義如下:
- /*
- * Class: java_lang_Thread
- * Method: start0
- * Signature: ()V
- */
- JNIEXPORT void JNICALL Java_java_lang_Thread_start0
- (JNIEnv *, jobject);
通過注釋 Method: start0 我可以猜到,在 jvm 的內部也可能會存在 start0 這個方法,于是我又搜索了一下這個方法,找到了 Thread.c 文件。可以看到里面有一個 Java_java_lang_Thread_registerNatives() 方法,這就是用來初始化在 Thread.java 與其他方法的綁定,并且在 Threa.java 的第一個 static 塊中就調用了這個方法,保證這個方法在類加載中是第一個被調用的方法。這個 native 方法的作用是為其他 native 方法注冊到JVM中。代碼如下所示:
- 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},
- {"setNativeName", "(" STR ")V", (void *)&JVM_SetNativeThreadName},
- };
- #undef THD
- #undef OBJ
- #undef STE
- #undef STR
- JNIEXPORT void JNICALL
- Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls)
- {
- (*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods));
- }
再回到我們的 start0 方法,此時我們就去查找 JVM_StartThread 方法是在他是在/hotspot/src/share/vm/prims/jvm.cpp 這個文件里面:
- JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
- JVMWrapper("JVM_StartThread");
- JavaThread *native_thread = NULL;
- // We cannot hold the Threads_lock when we throw an exception,
- // due to rank ordering issues. Example: we might need to grab the
- // Heap_lock while we construct the exception.
- bool throw_illegal_thread_state = false;
- // We must release the Threads_lock before we can post a jvmti event
- // in Thread::start.
- {
- // Ensure that the C++ Thread and OSThread structures aren't freed before
- // we operate.
- MutexLocker mu(Threads_lock);
- // 1. 判斷 Java 線程是否啟動,如果已經啟動,拋出異常
- if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
- throw_illegal_thread_state = true;
- } else {
- // 2. 如果沒有創建,則會創建線程
- jlong size =
- java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
- size_t sz = size > 0 ? (size_t) size : 0;
- // 虛擬機創建 JavaThread, 該類內部會創建操作系統線程,然后關聯 Java 線程
- native_thread = new JavaThread(&thread_entry, sz);
- if (native_thread->osthread() != NULL) {
- // Note: the current thread is not being used within "prepare".
- native_thread->prepare(jthread);
- }
- }
- }
- if (throw_illegal_thread_state) {
- THROW(vmSymbols::java_lang_IllegalThreadStateException());
- }
- assert(native_thread != NULL, "Starting null thread?");
- if (native_thread->osthread() == NULL) {
- // No one should hold a reference to the 'native_thread'.
- delete native_thread;
- if (JvmtiExport::should_post_resource_exhausted()) {
- JvmtiExport::post_resource_exhausted(
- JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
- "unable to create new native thread");
- }
- THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
- "unable to create new native thread");
- }
- // 設置線程狀態為 Runnable
- Thread::start(native_thread);
- JVM_END
JavaThread 類的構造方法我們一起來看看,他是通過 os::create_thread 函數來進行創建 Java 對應的內核線程
- JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
- Thread()
- {
- if (TraceThreadEvents) {
- tty->print_cr("creating thread %p", this);
- }
- initialize();
- _jni_attach_state = _not_attaching_via_jni;
- set_entry_point(entry_point);
- os::ThreadType thr_type = os::java_thread;
- thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
- os::java_thread;
- // 創建Java線程對應的內核線
- os::create_thread(this, thr_type, stack_sz);
- _safepoint_visible = false;
- }
os:create_thread 其實主要就是一個用來支持跨平臺創建線程的, 以 Linux 為例 (hotspot/src/os/linux/vm/os_linux.cpp):
- bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
- // ...
- // 創建 OSThread 內核線程對象
- OSThread* osthread = new OSThread(NULL, NULL);
- // 綁定
- thread->set_osthread(osthread);
- pthread_t tid;
- // pthread_create 為 linux api 用來創建線程。
- int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
- // ...
- return true;
- }
我們可以通過 ubantu 的控制臺來查詢接口信息
- man pthread_create 來進行查詢文檔
通過文檔我們可以了解,當 pthread_create 函數執行創建完線程之后會調用第三個參數傳遞過去的回調函數
- int ret = pthread_create(&tid, &attr, (void* ()(void)) java_start, thread);
在這里就是 java_start 函數
- // Thread start routine for all newly created threads
- static void *java_start(Thread *thread) {
- // 主要是調用 Thread 的 run 方法
- thread->run();
- return 0;
- }
在 thread.cpp 中 JavaThread::run 方法最終調用了 thread_main_inner 方法:
- // The first routine called by a new Java thread
- void JavaThread::run() {
- // We call another function to do the rest so we are sure that the stack addresses used
- // from there will be lower than the stack base just computed
- thread_main_inner();
- // Note, thread is no longer valid at this point!
- }
在 thread_main_inner 方法內,在調用咱們之前創建 JavaThread 對象的時候傳遞進來的 entry_point 方法:
- void JavaThread::thread_main_inner() {
- if (!this->has_pending_exception() &&
- !java_lang_Thread::is_stillborn(this->threadObj())) {
- {
- ResourceMark rm(this);
- this->set_native_thread_name(this->get_thread_name());
- }
- HandleMark hm(this);
- // 調用 entry_point 方法
- this->entry_point()(this, this);
- }
- DTRACE_THREAD_PROBE(stop, this);
- this->exit(false);
- delete this;
- }
通過上面的代碼我們可以看到先創建了一個 JavaThread 對象, 然后傳入了 thread_entry 方法
- // JVM_StartThread 創建操作系統線程,執行 thread_entry 函數
- static void thread_entry(JavaThread* thread, TRAPS) {
- HandleMark hm(THREAD);
- Handle obj(THREAD, thread->threadObj());
- JavaValue result(T_VOID);
- // Thrad.start() 調用 java.lang.Thread 類的 run 方法
- JavaCalls::call_virtual(&result,
- obj,
- KlassHandle(THREAD, SystemDictionary::Thread_klass()),
- vmSymbols::run_method_name(),
- vmSymbols::void_method_signature(),
- THREAD);
- }
我們再來看看我們 Java 中 Thread 類的 run 方法
- public void run() {
- if (target != null) {
- // Thread.run() 又調用 Runnable.run()
- target.run();
- }
- }
參考資料
https://www.jb51.net/article/216231.htm
https://blog.csdn.net/u013928208/article/details/108051796
https://www.cnblogs.com/whhjava/p/9916626.html
https://www.runoob.com/w3cnote/jni-getting-started-tutorials.html
https://developer.51cto.com/art/202011/632936.htm
https://blog.csdn.net/weixin_34384681/article/details/90660510
https://blog.csdn.net/weixin_30267697/article/details/95994035
https://zhuanlan.zhihu.com/p/33830504