您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)怎么啟動Java 線程的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
new Thread(() -> { // todo }).start();
咳咳,Java 的線程創(chuàng)建和啟動非常簡單,但如果問一個(gè)線程是怎么啟動起來的往往并不清楚,甚至不知道為什么啟動時(shí)是調(diào)用start(),而不是調(diào)用run()方法呢?
那么,為了讓大家有一個(gè)更直觀的認(rèn)知,我們先站在上帝視角。把這段 Java
的線程代碼,到 JDK 方法使用,以及 JVM 的相應(yīng)處理過程,展示給大家,以方便我們后續(xù)逐步分析。
以上,就是一個(gè)線程啟動的整體過程分析,會涉及到如下知識點(diǎn):
線程的啟動會涉及到本地方法(JNI)的調(diào)用,也就是那部分 C++ 編寫的代碼。
JVM 的實(shí)現(xiàn)中會有不同操作系統(tǒng)對線程的統(tǒng)一處理,比如:Win、Linux、Unix。
線程的啟動會涉及到線程的生命周期狀態(tài)(RUNNABLE),以及喚醒操作,所以最終會有回調(diào)操作。也就是調(diào)用我們的 run() 方法
接下來,我們就開始逐步分析每一步源碼的執(zhí)行內(nèi)容,從而了解線程啟動過程。
這是線程的啟動過程時(shí)序圖,整體的鏈路較長,會涉及到 JVM 的操作。核心源碼如下:
Thread.c
jvm.cpp
thread.cpp
os.cpp
os_linux.cpp
os_windows.cpp
vmSymbols.hpp
new Thread(() -> { // todo }).start(); // JDK 源碼 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) {} } }
線程啟動方法 start(),在它的方法英文注釋中已經(jīng)把核心內(nèi)容描述出來。Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
這段話的意思是:由 JVM 調(diào)用此線程的 run 方法,使線程開始執(zhí)行。其實(shí)這就是一個(gè) JVM 的回調(diào)過程,下文源碼分析中會講到
另外 start() 是一個(gè) synchronized 方法,但為了避免多次調(diào)用,在方法中會由線程狀態(tài)判斷。threadStatus != 0
。group.add(this),
是把當(dāng)前線程加入到線程組,ThreadGroup
。
start0(),是一個(gè)本地方法,通過 JNI 方式調(diào)用執(zhí)行。這一步的操作才是啟動線程的核心步驟。
// 本地方法 start0 private native void start0(); // 注冊本地方法 public class Thread implements Runnable { /* Make sure registerNatives is the first thing <clinit> does. */ private static native void registerNatives(); static { registerNatives(); } // ... }
start0(),
是一個(gè)本地方法,用于啟動線程。
registerNatives(),
這個(gè)方法是用于注冊線程執(zhí)行過程中需要的一些本地方法,比如:start0、isAlive、yield、sleep、interrupt0等。
registerNatives
,本地方法定義在 Thread.c 中,以下是定義的核心源碼:
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}, {"interrupt0", "()V", (void *)&JVM_Interrupt}, {"holdsLock", "(" OBJ ")Z", (void *)&JVM_HoldsLock}, {"getThreads", "()[" THD, (void *)&JVM_GetAllThreads}, {"dumpThreads", "([" THD ")[[" STE, (void *)&JVM_DumpThreads}, {"setNativeName", "(" STR ")V", (void *)&JVM_SetNativeThreadName}, };
從定義中可以看到,start0 方法會執(zhí)行 &JVM_StartThread
方法,最終由 JVM 層面啟動線程。
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) JVMWrapper("JVM_StartThread"); JavaThread *native_thread = NULL; // 創(chuàng)建線程 native_thread = new JavaThread(&thread_entry, sz); // 啟動線程 Thread::start(native_thread); JVM_END
這部分代碼比較多,但核心內(nèi)容主要是創(chuàng)建線程和啟動線程,另外 &thread_entry
也是一個(gè)方法,如下:thread_entry
,線程入口
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()), vmSymbols::run_method_name(), vmSymbols::void_method_signature(), THREAD); }
重點(diǎn),在創(chuàng)建線程引入這個(gè)線程入口的方法時(shí),thread_entry 中包括了 Java 的回調(diào)函數(shù) JavaCalls::call_virtual
。這個(gè)回調(diào)函數(shù)會由 JVM 調(diào)用。
vmSymbols::run_method_name(),就是那個(gè)被回調(diào)的方法,源碼如下:
#define VM_SYMBOLS_DO(template, do_alias) template(run_method_name, "run")
這個(gè) run 就是我們的 Java 程序中會被調(diào)用的 run 方法。接下來我們繼續(xù)按照代碼執(zhí)行鏈路,尋找到這個(gè)被回調(diào)的方法在什么時(shí)候調(diào)用的。
native_thread = new JavaThread(&thread_entry, sz);
接下來,我們繼續(xù)看 JavaThread
的源碼執(zhí)行內(nèi)容。
JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : Thread() #if INCLUDE_ALL_GCS , _satb_mark_queue(&_satb_mark_queue_set), _dirty_card_queue(&_dirty_card_queue_set) #endif // INCLUDE_ALL_GCS { if (TraceThreadEvents) { tty->print_cr("creating thread %p", this); } initialize(); _jni_attach_state = _not_attaching_via_jni; set_entry_point(entry_point); // Create the native thread itself. // %note runtime_23 os::ThreadType thr_type = os::java_thread; thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :os::java_thread; os::create_thread(this, thr_type, stack_sz); }
ThreadFunction entry_point
,就是我們上面的 thread_entry
方法。
size_t stack_sz
,表示進(jìn)程中已有的線程個(gè)數(shù)。
這兩個(gè)參數(shù),都會傳遞給 os::create_thread
方法,用于創(chuàng)建線程使用。
源碼:
os_linux.cpp:
os_windows.cpp:
眾所周知,JVM 是個(gè)啥!,所以它的 OS 服務(wù)實(shí)現(xiàn),Liunx 還有 Windows
等,都會實(shí)現(xiàn)線程的創(chuàng)建邏輯。這有點(diǎn)像適配器模式
os_linux -> os::create_thread bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { assert(thread->osthread() == NULL, "caller responsible"); // Allocate the OSThread object OSThread* osthread = new OSThread(NULL, NULL); // Initial state is ALLOCATED but not INITIALIZED osthread->set_state(ALLOCATED); pthread_t tid; int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); return true; }
osthread->set_state(ALLOCATED),
初始化已分配的狀態(tài),但此時(shí)并沒有初始化。pthread_create
,是類Unix操作系統(tǒng)(Unix、Linux、Mac OS X等)的創(chuàng)建線程的函數(shù)。java_start
,重點(diǎn)關(guān)注類,是實(shí)際創(chuàng)建線程的方法。
static void *java_start(Thread *thread) { // 線程ID int pid = os::current_process_id(); // 設(shè)置線程 ThreadLocalStorage::set_thread(thread); // 設(shè)置線程狀態(tài):INITIALIZED 初始化完成 osthread->set_state(INITIALIZED); // 喚醒所有線程 sync->notify_all(); // 循環(huán),初始化狀態(tài),則一致等待 wait while (osthread->get_state() == INITIALIZED) { sync->wait(Mutex::_no_safepoint_check_flag); } // 等待喚醒后,執(zhí)行 run 方法 thread->run(); return 0; }
JVM
設(shè)置線程狀態(tài),INITIALIZED 初始化完成。sync->notify_all(),
喚醒所有線程。osthread->get_state() == INITIALIZED
,while 循環(huán)等待thread->run(),
是等待線程喚醒后,也就是狀態(tài)變更后,才能執(zhí)行到。這在我們的線程執(zhí)行UML圖中,也有所體現(xiàn)
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) JVMWrapper("JVM_StartThread"); JavaThread *native_thread = NULL; // 創(chuàng)建線程 native_thread = new JavaThread(&thread_entry, sz); // 啟動線程 Thread::start(native_thread); JVM_END
JVM_StartThread
中有兩步,創(chuàng)建(new JavaThread
)、啟動(Thread::start
)。創(chuàng)建的過程聊完了,接下來我們聊啟動。
void Thread::start(Thread* thread) { trace("start", thread); if (!DisableStartThread) { if (thread->is_Java_thread()) { java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), java_lang_Thread::RUNNABLE); } // 不同的 OS 會有不同的啟動代碼邏輯 os::start_thread(thread); } }
如果沒有禁用線程 DisableStartThread
并且是 Java 線程 thread->is_Java_thread(),
那么設(shè)置線程狀態(tài)為 RUNNABLE。os::start_thread(thread),
調(diào)用線程啟動方法。不同的 OS 會有不同的啟動代碼邏輯
void os::start_thread(Thread* thread) { // guard suspend/resume MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag); OSThread* osthread = thread->osthread(); osthread->set_state(RUNNABLE); pd_start_thread(thread); }
osthread->set_state(RUNNABLE)
,設(shè)置線程狀態(tài) RUNNABLEpd_start_thread(thread)
,啟動線程,這個(gè)就由各個(gè) OS 實(shí)現(xiàn)類,實(shí)現(xiàn)各自系統(tǒng)的啟動方法了。比如,windows系統(tǒng)和Linux系統(tǒng)的代碼是完全不同的。
void os::pd_start_thread(Thread* thread) { OSThread * osthread = thread->osthread(); assert(osthread->get_state() != INITIALIZED, "just checking"); Monitor* sync_with_child = osthread->startThread_lock(); MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); sync_with_child->notify(); }
這部分代碼 notify() 最關(guān)鍵,它可以喚醒線程。
線程喚醒后,3.4 中的 thread->run(); 就可以繼續(xù)執(zhí)行了。
// The first routine called by a new Java thread void JavaThread::run() { // ... 初始化線程操作 thread_main_inner(); }
os_linux.cpp 類中的 java_start 里的 thread->run(),最終調(diào)用的就是 thread.cpp 的 JavaThread::run() 方法。
這部分還需要繼續(xù)往下看,thread_main_inner(); 方法。
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); this->entry_point()(this, this); } DTRACE_THREAD_PROBE(stop, this); this->exit(false); delete this; }
這里有你熟悉的設(shè)置的線程名稱,this->set_native_thread_name(this->get_thread_name())
。
this->entry_point(),實(shí)際調(diào)用的就是 3.1 中的 thread_entry 方法。
thread_entry,方法最終會調(diào)用到 JavaCalls::call_virtual 里的vmSymbols::run_method_name()。
也就是 run() 方法,至此線程啟動完成。終于串回來了!
感謝各位的閱讀!關(guān)于“怎么啟動Java 線程”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。