Java 当中的线程和操作系统的线程是什么关系?

873 阅读2分钟

1. 在linux 系统中,操作系统的线程控制原语

                 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);               

通过 命令: man pthread_create 可以看到如下描述:

根据man配置的信息可以得出pthread_create会创建一个线程,这个函数是linux系统的函数,可以用C或者C++直接调用,这个函数在pthread.h
pthread_t *thread
传出参数,调用之后会传出被创建线程的id
定义 pthread_t pid;
继而 取地址 &pid
const pthread_attr_t *attr
线程属性,关于线程属性是linux的知识
在学习pthread_create函数的时候一般穿NULL,保持默认属性
void *(*start_routine) (void *)
线程的启动后的主体函数
相当于java当中的run
需要你定义一个函数,然后传函数名即可
void *arg
主体函数的参数
如果没有可以传NULL
在linux上启动一个线程的代码:
#include <pthread.h>//头文件
#include <stdio.h>
pthread_t pid;//定义一个变量,接受创建线程后的线程id
//定义线程的主体函数
void* thread_entity(void* arg)
{   
    printf("i am new Thread!");
}
//main方法,程序入口,main和java的main一样会产生一个进程,继而产生一个main线程
int main()
{
    //调用操作系统的函数创建线程,注意四个参数
    pthread_create(&pid,NULL,thread_entity,NULL);
    //usleep是睡眠的意思,那么这里的睡眠是让谁睡眠呢?
    //为什么需要睡眠?如果不睡眠会出现什么情况
    usleep(100);
    printf("main\n");
}
在java代码里启动一个线程的代码
 public class MyStart {

    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                System.out.println("i am new Thread!");
            }
        }; 
        thread.start();
    }
}
这里启动的线程和上面我们通过linux的pthread_create函数启动的线程有什么关系呢?
只能去可以查看start()的源码了,看看java的start()到底干了什么事才能对比出来.
start源码的部分截图,可以看到这个方法最核心的就是调用了一个start0方法,而start0方法又是一个native方法,故而如果要搞明白start0我们需要查看Hotspot的源码.

总结:
jdk---->sun 提供的Java库(C 文件)--》1. 实现调用操作系统的函数 2. 调用jvm的代码hostpot

java  中 thread.start()  =====> os 中 pthread_create--->线程

因为 Java的线程和操作系统os的线程是 1:1 对应的