闲话少叙,先抛出两个问题
- java当中的线程和操作系统的线程是什么关系?
- 调用Thread的start方法,为什么会调用对应的run方法?
要回答这两个问题,都绕不开一个关键点——无论通过什么框架,调用多少个线程的api,归根结底,都是在操作系统开启了一个线程。
下面介绍一下linux系统,有关线程的控制原语(可以理解为函数)
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
pthread_create 就是linux暴露出来的创建一个线程的原语,相关参数解释如下
pthread_t *thread |
传出参数,调用之后会传出被创建线程的id |
定义 pthread_t pid; 继而 取地址 &pid |
const pthread_attr_t *attr |
线程属性,关于线程属性是linux的知识 |
在学习pthread_create函数的时候一般穿NULL,保持默认属性 |
void *(*start_routine) (void *) |
线程的启动后的主体函数 相当于java当中的run |
需要你定义一个函数,然后传 |