Welcome 微信登录

首页 / 操作系统 / Linux / Java 工具(jmap,jstack)在Linux上的源码分析(三)执行的线程vm thread

在前面的文章中(http://www.linuxidc.com/Linux/2012-01/51213.htm)所提到的信号转发线程,Attach Listener 线程都只是操作socket文件,并没有去执行比如stack 分析,或者heap的分析,真正的工作线程其实是vm thread.(一)启动vm thread
  1. jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {  
  2. ...  
  3.   // Create the VMThread   
  4.   { TraceTime timer("Start VMThread", TraceStartupTime);  
  5.     VMThread::create();  
  6.     Thread* vmthread = VMThread::vm_thread();  
  7.   
  8.     if (!os::create_thread(vmthread, os::vm_thread))  
  9.       vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");  
  10.   
  11.     // Wait for the VM thread to become ready, and VMThread::run to initialize   
  12.     // Monitors can have spurious returns, must always check another state flag   
  13.     {  
  14.       MutexLocker ml(Notify_lock);  
  15.       os::start_thread(vmthread);  
  16.       while (vmthread->active_handles() == NULL) {  
  17.         Notify_lock->wait();  
  18.       }  
  19.     }  
  20.   }  
  21. ...  
  22.   
  23.   
  24. }  
我们可以看到,在thread.cpp里启动了线程vm thread,在这里我们同时也稍微的略带的讲一下jvm在linux里如何启动线程的。通常在linux中启动线程,是调用
  1. 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的方法
  1. bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {  
  2. ....  
  3. int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);  
  4. ....  
  5. }  
继续看java_start方法
  1. static void *java_start(Thread *thread) {  
  2. ....  
  3.   // handshaking with parent thread   
  4.   {  
  5.     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);  
  6.   
  7.     // notify parent thread   
  8.     osthread->set_state(INITIALIZED);  
  9.     sync->notify_all();  
  10.   
  11.     // wait until os::start_thread()   
  12.     while (osthread->get_state() == INITIALIZED) {  
  13.       sync->wait(Mutex::_no_safepoint_check_flag);  
  14.     }  
  15.   }  
  16.   
  17.   // call one more level start routine   
  18.   thread->run();  
  19.   
  20.   return 0;  
  21. }  
首先jvm先设置了当前线程的状态是Initialized, 然后notify所有的线程, while (osthread->get_state() == INITIALIZED) {
      sync->wait(Mutex::_no_safepoint_check_flag);
    }不停的查看线程的当前状态是不是Initialized, 如果是的话,调用了sync->wait()的方法等待。来看os:start_thread的方法 os.cpp
  1. void os::start_thread(Thread* thread) {  
  2.   // guard suspend/resume   
  3.   MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);  
  4.   OSThread* osthread = thread->osthread();  
  5.   osthread->set_state(RUNNABLE);  
  6.   pd_start_thread(thread);  
  7. }