在前面的文章中(http://www.linuxidc.com/Linux/2012-01/51213.htm)所提到的信號轉發線程,Attach Listener 線程都只是操作socket文件,並沒有去執行比如stack 分析,或者heap的分析,真正的工作線程其實是vm thread.
(一)啟動vm thread
- jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
- ...
- // Create the VMThread
- { TraceTime timer("Start VMThread", TraceStartupTime);
- VMThread::create();
- Thread* vmthread = VMThread::vm_thread();
-
- if (!os::create_thread(vmthread, os::vm_thread))
- vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
-
- // Wait for the VM thread to become ready, and VMThread::run to initialize
- // Monitors can have spurious returns, must always check another state flag
- {
- MutexLocker ml(Notify_lock);
- os::start_thread(vmthread);
- while (vmthread->active_handles() == NULL) {
- Notify_lock->wait();
- }
- }
- }
- ...
-
-
- }
我們可以看到,在thread.cpp裡啟動了線程vm thread,在這裡我們同時也稍微的略帶的講一下jvm在linux裡如何啟動線程的。
通常在linux中啟動線程,是調用
- int pthread_create((pthread_t *__thread, __const pthread_attr_t *__attr,void *(*__start_routine) (void *), void *__arg));
而在java裡卻增加了os:create_thread --初始化線程 和os:start_thread--啟動線程
我們去看一下jvm裡面是如何在linux裡做到的
在os_linux.cpp中來看create_thread的方法
- bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
- ....
- int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
- ....
- }
繼續看java_start方法
- static void *java_start(Thread *thread) {
- ....
- // handshaking with parent thread
- {
- MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
-
- // notify parent thread
- osthread->set_state(INITIALIZED);
- sync->notify_all();
-
- // wait until os::start_thread()
- while (osthread->get_state() == INITIALIZED) {
- sync->wait(Mutex::_no_safepoint_check_flag);
- }
- }
-
- // call one more level start routine
- thread->run();
-
- return 0;
- }
首先jvm先設置了當前線程的狀態是Initialized, 然後notify所有的線程,
while (osthread->get_state() == INITIALIZED) {
sync->wait(Mutex::_no_safepoint_check_flag);
}
不停的查看線程的當前狀態是不是Initialized, 如果是的話,調用了sync->wait()的方法等待。
來看os:start_thread的方法 os.cpp
- 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);
- }