成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

從 Hotspot 虛擬機角度來分析 Java 線程啟動

開發 后端
Java 線程其實是映射到操作系統的內核線程上的,所以 Java 線程基本上也就是操作系統在進行管理。在 Linux系統中,線程和進程用的是同一個結構體進行描述的,只不過進程擁有自己獨立的地址空間,而同一個進程的多個線程之間是共享資源的。

[[422986]]

基本概念

Java 線程其實是映射到操作系統的內核線程上的,所以 Java 線程基本上也就是操作系統在進行管理。在 Linux系統中,線程和進程用的是同一個結構體進行描述的,只不過進程擁有自己獨立的地址空間,而同一個進程的多個線程之間是共享資源的。

簡單說明:本文基于 openjdk 1.8 進行

線程狀態

每種線程狀態的切換條件, 以及調用方法如下圖所示 :

線程具有以下幾種狀態 Java 的線程狀態在 Thread.State 枚舉中定義代碼如下

  1. public enum State { 
  2.     //新創建,未啟動 
  3.     NEW, 
  4.  
  5.     //在jvm 中運行,也可能正在等待操作系統的其他資源 
  6.     RUNNABLE, 
  7.  
  8.     //阻塞,并且正在等待監視器鎖 
  9.     BLOCKED, 
  10.  
  11.     //處于等待狀態的線程,正在等待另一個線程執行特定的操作 
  12.     WAITING, 
  13.  
  14.     //限期等待, 可以設置最大等待時間 
  15.     TIMED_WAITING, 
  16.  
  17.     //結束 
  18.     TERMINATED; 

線程創建

繼承 Thread 類, 代碼如下:

  1. class PrimeThread extends Thread { 
  2.     long minPrime; 
  3.     PrimeThread(long minPrime) { 
  4.         this.minPrime = minPrime; 
  5.     } 
  6.  
  7.     public void run() { 
  8.         // compute primes larger than minPrime 
  9.         . . . 
  10.         } 
  11.  
  12. // 啟動線程 
  13. PrimeThread p = new PrimeThread(143); 
  14. p.start(); 

實現 Runable 接口, 代碼如下 (通常推薦使用這種方式):

  1. class PrimeRun implements Runnable { 
  2.     long minPrime; 
  3.     PrimeRun(long minPrime) { 
  4.         this.minPrime = minPrime; 
  5.     } 
  6.  
  7.     public void run() { 
  8.         // compute primes larger than minPrime 
  9.         . . . 
  10.         } 
  11.  
  12. // 啟動線程 
  13. PrimeRun p = new PrimeRun(143); 
  14. 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和其他語言之間的耦合。

舉個例子 這塊操作比較多,可以參考如下的資料

  1. https://www.runoob.com/w3cnote/jni-getting-started-tutorials.html 

啟動流程

啟動流程如下

線程啟動

Java 創建線程 Thread 實例之后,是通過 start 方法進行啟動該線程,通知執行。在 start 方法的內部,調用的是 start0() 這個本地方法。我們可以從該方法為入口分析 JVM 對于 Thread 的底層實現。

  1. public synchronized void start() { 
  2.     // 判斷線程狀態 
  3.     if (threadStatus != 0) 
  4.         throw new IllegalThreadStateException(); 
  5.  
  6.     // 添加到組 
  7.     group.add(this); 
  8.  
  9.     boolean started = false
  10.     try { 
  11.         // 啟動線程 
  12.         start0(); 
  13.         started = true
  14.     } finally { 
  15.         try { 
  16.             if (!started) { 
  17.                 group.threadStartFailed(this); 
  18.             } 
  19.         } catch (Throwable ignore) { 
  20.             /* do nothing. If start0 threw a Throwable then 
  21.               it will be passed up the call stack */ 
  22.         } 
  23.     } 
  24.  
  25. private native void start0(); 

start0() 是一個本地方法,咱們按照 JNI 規范可以到 hotspot 虛擬源碼中查找 java_lang_Thread_start0 這個函數。定義如下:

  1. /* 
  2.  * Class:     java_lang_Thread 
  3.  * Method:    start0 
  4.  * Signature: ()V 
  5.  */ 
  6. JNIEXPORT void JNICALL Java_java_lang_Thread_start0 
  7.   (JNIEnv *, jobject); 

通過注釋 Method: start0 我可以猜到,在 jvm 的內部也可能會存在 start0 這個方法,于是我又搜索了一下這個方法,找到了 Thread.c 文件。可以看到里面有一個 Java_java_lang_Thread_registerNatives() 方法,這就是用來初始化在 Thread.java 與其他方法的綁定,并且在 Threa.java 的第一個 static 塊中就調用了這個方法,保證這個方法在類加載中是第一個被調用的方法。這個 native 方法的作用是為其他 native 方法注冊到JVM中。代碼如下所示:

  1. static JNINativeMethod methods[] = { 
  2.     {"start0",           "()V",        (void *)&JVM_StartThread}, 
  3.     {"stop0",            "(" OBJ ")V", (void *)&JVM_StopThread}, 
  4.     {"isAlive",          "()Z",        (void *)&JVM_IsThreadAlive}, 
  5.     {"suspend0",         "()V",        (void *)&JVM_SuspendThread}, 
  6.     {"resume0",          "()V",        (void *)&JVM_ResumeThread}, 
  7.     {"setPriority0",     "(I)V",       (void *)&JVM_SetThreadPriority}, 
  8.     {"yield",            "()V",        (void *)&JVM_Yield}, 
  9.     {"sleep",            "(J)V",       (void *)&JVM_Sleep}, 
  10.     {"currentThread",    "()" THD,     (void *)&JVM_CurrentThread}, 
  11.     {"countStackFrames""()I",        (void *)&JVM_CountStackFrames}, 
  12.     {"interrupt0",       "()V",        (void *)&JVM_Interrupt}, 
  13.     {"isInterrupted",    "(Z)Z",       (void *)&JVM_IsInterrupted}, 
  14.     {"holdsLock",        "(" OBJ ")Z", (void *)&JVM_HoldsLock}, 
  15.     {"getThreads",        "()[" THD,   (void *)&JVM_GetAllThreads}, 
  16.     {"dumpThreads",      "([" THD ")[[" STE, (void *)&JVM_DumpThreads}, 
  17.     {"setNativeName",    "(" STR ")V", (void *)&JVM_SetNativeThreadName}, 
  18. }; 
  19.  
  20. #undef THD 
  21. #undef OBJ 
  22. #undef STE 
  23. #undef STR 
  24.  
  25. JNIEXPORT void JNICALL 
  26. Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls) 
  27.     (*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods)); 

再回到我們的 start0 方法,此時我們就去查找 JVM_StartThread 方法是在他是在/hotspot/src/share/vm/prims/jvm.cpp 這個文件里面:

  1. JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) 
  2.   JVMWrapper("JVM_StartThread"); 
  3.   JavaThread *native_thread = NULL
  4.  
  5.   // We cannot hold the Threads_lock when we throw an exception, 
  6.   // due to rank ordering issues. Example:  we might need to grab the 
  7.   // Heap_lock while we construct the exception. 
  8.   bool throw_illegal_thread_state = false
  9.  
  10.   // We must release the Threads_lock before we can post a jvmti event 
  11.   // in Thread::start. 
  12.   { 
  13.     // Ensure that the C++ Thread and OSThread structures aren't freed before 
  14.     // we operate. 
  15.     MutexLocker mu(Threads_lock); 
  16.  
  17.     // 1. 判斷 Java 線程是否啟動,如果已經啟動,拋出異常 
  18.     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) { 
  19.       throw_illegal_thread_state = true
  20.     } else { 
  21.       // 2. 如果沒有創建,則會創建線程  
  22.       jlong size = 
  23.              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));   
  24.       size_t sz = size > 0 ? (size_t) size : 0; 
  25.       // 虛擬機創建 JavaThread, 該類內部會創建操作系統線程,然后關聯 Java 線程   
  26.       native_thread = new JavaThread(&thread_entry, sz); 
  27.  
  28.       if (native_thread->osthread() != NULL) { 
  29.         // Note: the current thread is not being used within "prepare"
  30.         native_thread->prepare(jthread); 
  31.       } 
  32.     } 
  33.   } 
  34.  
  35.   if (throw_illegal_thread_state) { 
  36.     THROW(vmSymbols::java_lang_IllegalThreadStateException()); 
  37.   } 
  38.  
  39.   assert(native_thread != NULL"Starting null thread?"); 
  40.  
  41.   if (native_thread->osthread() == NULL) { 
  42.     // No one should hold a reference to the 'native_thread'
  43.     delete native_thread; 
  44.     if (JvmtiExport::should_post_resource_exhausted()) { 
  45.       JvmtiExport::post_resource_exhausted( 
  46.         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS, 
  47.         "unable to create new native thread"); 
  48.     } 
  49.     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 
  50.               "unable to create new native thread"); 
  51.   } 
  52.  
  53.   // 設置線程狀態為 Runnable 
  54.   Thread::start(native_thread); 
  55.  
  56. JVM_END 

JavaThread 類的構造方法我們一起來看看,他是通過 os::create_thread 函數來進行創建 Java 對應的內核線程

  1. JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : 
  2.   Thread() 
  3.   if (TraceThreadEvents) { 
  4.     tty->print_cr("creating thread %p", this); 
  5.   } 
  6.   initialize(); 
  7.   _jni_attach_state = _not_attaching_via_jni; 
  8.   set_entry_point(entry_point); 
  9.   os::ThreadType thr_type = os::java_thread; 
  10.   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : 
  11.                                                      os::java_thread; 
  12.   // 創建Java線程對應的內核線 
  13.   os::create_thread(this, thr_type, stack_sz); 
  14.   _safepoint_visible = false

os:create_thread 其實主要就是一個用來支持跨平臺創建線程的, 以 Linux 為例 (hotspot/src/os/linux/vm/os_linux.cpp):

  1. bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 
  2.   // ... 
  3.    
  4.   // 創建 OSThread 內核線程對象 
  5.   OSThread* osthread = new OSThread(NULLNULL); 
  6.   // 綁定 
  7.   thread->set_osthread(osthread); 
  8.  
  9.   pthread_t tid; 
  10.   // pthread_create 為 linux api 用來創建線程。 
  11.   int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 
  12.   // ...   
  13.   return true

我們可以通過 ubantu 的控制臺來查詢接口信息

  • man pthread_create 來進行查詢文檔

通過文檔我們可以了解,當 pthread_create 函數執行創建完線程之后會調用第三個參數傳遞過去的回調函數

  • int ret = pthread_create(&tid, &attr, (void* ()(void)) java_start, thread);

在這里就是 java_start 函數

  1. // Thread start routine for all newly created threads 
  2. static void *java_start(Thread *thread) { 
  3.  
  4.   // 主要是調用 Thread 的 run 方法 
  5.   thread->run(); 
  6.  
  7.   return 0; 

在 thread.cpp 中 JavaThread::run 方法最終調用了 thread_main_inner 方法:

  1. // The first routine called by a new Java thread 
  2. void JavaThread::run() { 
  3.   
  4.  
  5.   // We call another function to do the rest so we are sure that the stack addresses used 
  6.   // from there will be lower than the stack base just computed 
  7.   thread_main_inner(); 
  8.  
  9.   // Note, thread is no longer valid at this point! 

在 thread_main_inner 方法內,在調用咱們之前創建 JavaThread 對象的時候傳遞進來的 entry_point 方法:

  1. void JavaThread::thread_main_inner() { 
  2.  
  3.   if (!this->has_pending_exception() && 
  4.       !java_lang_Thread::is_stillborn(this->threadObj())) { 
  5.     { 
  6.       ResourceMark rm(this); 
  7.       this->set_native_thread_name(this->get_thread_name()); 
  8.     } 
  9.     HandleMark hm(this); 
  10.     // 調用 entry_point 方法 
  11.     this->entry_point()(this, this); 
  12.   } 
  13.  
  14.   DTRACE_THREAD_PROBE(stop, this); 
  15.  
  16.   this->exit(false); 
  17.   delete this; 

通過上面的代碼我們可以看到先創建了一個 JavaThread 對象, 然后傳入了 thread_entry 方法

  1. // JVM_StartThread 創建操作系統線程,執行  thread_entry 函數 
  2. static void thread_entry(JavaThread* thread, TRAPS) { 
  3.   HandleMark hm(THREAD); 
  4.   Handle obj(THREAD, thread->threadObj()); 
  5.   JavaValue result(T_VOID); 
  6.   // Thrad.start() 調用 java.lang.Thread 類的 run 方法 
  7.   JavaCalls::call_virtual(&result, 
  8.                           obj, 
  9.                           KlassHandle(THREAD, SystemDictionary::Thread_klass()), 
  10.                           vmSymbols::run_method_name(), 
  11.                           vmSymbols::void_method_signature(), 
  12.                           THREAD); 

我們再來看看我們 Java 中 Thread 類的 run 方法

  1. public void run() { 
  2.     if (target != null) { 
  3.         // Thread.run() 又調用 Runnable.run() 
  4.         target.run();  
  5.     } 

參考資料

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

 

責任編輯:武曉燕 來源: 運維開發故事
相關推薦

2020-09-02 07:03:04

虛擬機HotSpotJava

2010-11-05 09:47:11

OracleJava虛擬機

2012-08-16 09:07:57

Erlang

2012-08-06 09:26:19

Java虛擬機垃圾回收

2019-03-19 15:30:42

程序員JVM虛擬機

2009-06-12 16:15:42

死鎖Java虛擬機

2025-01-24 00:00:00

JavaHotSpot虛擬機

2010-02-22 17:39:22

CentOS vmwa

2010-02-26 15:28:15

Python虛擬機

2017-11-14 16:43:13

Java虛擬機線程

2017-03-01 20:08:36

PHP內核分析

2012-05-18 10:22:23

2011-04-07 13:40:02

ezjailjail虛擬機

2013-07-17 09:32:58

2010-07-26 09:02:38

2020-06-03 19:07:49

Java虛擬機JVM

2010-09-17 15:12:57

JVMJava虛擬機

2023-06-28 15:53:25

虛擬機Linux

2019-08-01 08:00:04

AWS虛擬機Lightsail

2020-12-14 08:03:52

ArrayList面試源碼
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 美女视频一区 | 亚洲成人av| av中文字幕在线 | 欧美一级在线 | 久久一区二区视频 | 国产精品自拍视频 | 精品国产乱码久久久久久蜜退臀 | 亚洲精品福利视频 | 欧美综合久久 | eeuss国产一区二区三区四区 | 天天干天天操天天爽 | 国色天香综合网 | 日韩免费高清视频 | 欧美aⅴ片 | 国产精品一二三区 | 成人h动漫亚洲一区二区 | 亚洲欧美一区二区三区国产精品 | 狠狠色综合欧美激情 | 美国av毛片 | 国产精品美女 | 久久久久一区二区三区四区 | 亚洲欧美成人影院 | 日韩精品在线一区 | 97在线观看 | 亚洲一区 | 97视频精品 | 欧美一级黄色片免费观看 | av黄色免费在线观看 | 久久亚洲一区二区三区四区 | 精品三级 | 中文字幕一区在线观看视频 | 九九av| 日本欧美国产 | 欧美日韩中文字幕在线 | 2020国产在线| 成人在线免费观看视频 | av电影一区| 国产精品国产自产拍高清 | 日韩精品 电影一区 亚洲 | 中文字幕加勒比 | 91视频入口|