下面让我们来大概的分析下一个Java线程启动后,底层的调用细节。
环境:JDK:1.8
glibc:2-25
linux-kernel:2.6.0
![1240](http://upload-images.jianshu.io/upload_images/5058508-c5261bbd7c460e00.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
一JAVA 层面:
当我们创建一个线程并执行start()方法后这个线程才会被创建和执行。java.lang.Thread.start()方法会调用本地方法start0();
![1240](http://upload-images.jianshu.io/upload_images/5058508-6006ec97d3ad0409.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
二 JVM 层面:
接下来start0()方法会调用JVM_StartThread()方法:
![1240](http://upload-images.jianshu.io/upload_images/5058508-cff7b4db75f67e00.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这是JVM_StartThread的具体实现,可以看到,它会创建一个JavaThread实例。
![1240](http://upload-images.jianshu.io/upload_images/5058508-157cc6b20e4fec20.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
我们来看看JavaThread的构造方法里边发生了什么:
![1240](http://upload-images.jianshu.io/upload_images/5058508-0d48c41033e8595c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
os::create_thread的具体实现。在这个方法中会创建一个平台相关的OSThread 实例。
![1240](http://upload-images.jianshu.io/upload_images/5058508-b44a376c787347ac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
在os::create_thread()方法中会利用glibc库中的pthread.h中的pthread_create方法创建一个轻量级的Linux进程,这个方法执行后,线程创建控制流从JVM转到OS.
![1240](http://upload-images.jianshu.io/upload_images/5058508-c51f4441b8233d1d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
三 OS层:
pthread.h 中定义pthread_create()方法。
![1240](http://upload-images.jianshu.io/upload_images/5058508-e6c2465db291d013.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
pthread_create()方法的具体实现。
![1240](http://upload-images.jianshu.io/upload_images/5058508-daa7085803674d4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
pthread_create 方法进入clone方法的桥梁create_thread()方法。
![1240](http://upload-images.jianshu.io/upload_images/5058508-6ac3c14535c7a4b1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
create_thread方法的具体实现:
![1240](http://upload-images.jianshu.io/upload_images/5058508-28dc91b551e8028b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
系统调用:
![1240](http://upload-images.jianshu.io/upload_images/5058508-fd990e799f86c8dc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
系统调用的处理程序:sys_clone
![1240](http://upload-images.jianshu.io/upload_images/5058508-2a5ac0bc899234ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
do_fork()函数的具体实现:
![1240](http://upload-images.jianshu.io/upload_images/5058508-26c55fd934c57b41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
参考资料:①https://yq.aliyun.com/articles/67090? spm=5176.8091938.0.0.G8W8Xw
②http://blog.csdn.net/u011955950/article/details/45601985
③http://hllvm.group.iteye.com/group/topic/43599