java源码如何创建线程

转载自:http://blog.csdn.net/jeffhtlee/article/details/12751825
  1.  Java的线程是如何创建的,是直接调用OS的API,还是有自己的“抽象线程”?
这个还是看一下JDK的源码吧
先看java.lang.Thread.java中的start()方法:
[java]  view plain copy
  1. public synchronized void start()  
  2. {  
  3.     ...  
  4.     start0();  
  5.     ...  
  6. }  
  7.   
  8. private native void start0();  
start0()调用了本地方法,需要查看本地方法的实现。本地方法的源码可以到oracle网站去下载,网上找的这个地址 http://download.java.net/jdk6/source/ 。这个网址现在重定向到OpenJDK了。

解压后找到jdk\src\share\native\java\lang\Thread.c并查看,方法start0()映射到了JVM_StartThread这个方法中:
[cpp]  view plain copy
  1. static JNINativeMethod methods[] =   
  2. {  
  3.     {"start0",           "()V",        (void *)&JVM_StartThread},  
  4.     ..  
  5. }  

在hotspot\src\share\vm\prims\jvm.cpp查看JVM_StartThread的实现:
[cpp]  view plain copy
  1. JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))  
  2.     JavaThread *native_thread = NULL;  
  3.     ...  
  4.     native_thread = new JavaThread(&thread_entry, sz);  
  5.     ...  
  6.     Thread::start(native_thread);  
  7. JVM_END  

在hotspot\src\share\vm\runtime\thread.cpp中查看JavaThread的实现:
[cpp]  view plain copy
  1. JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz)  : ...  
  2. {  
  3.     ...  
  4.     os::create_thread(this, thr_type, stack_sz);  
  5. }  
  6.   
  7.   
  8. void Thread::start(Thread* thread)   
  9. {  
  10.     ...  
  11.     os::start_thread(thread);  
  12. }  

在hotspot\src\os目录下可以看到windows, linux, solaris和posix的实现,先检查linux\vm\os_linux.cpp
[cpp]  view plain copy
  1. bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size)   
  2. {  
  3.     ...  
  4.     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);  
  5.     ...  
  6. }  
pthread_create,POSIX中的API,呵呵。
所以问题也有答案了: 通过调用平台的API创建一个线程!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值