在java代码中启动一个线程
new Thread(() -> System.out.println("start...")).start();
查看源码:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();
可以看到start()方法最核心的就是调用了一个start0方法,而start0方法又是一个native方法,故而如果要搞明白start0我们需要查看Hotspot的源码,我们做个大胆的猜测,java级别的线程其实就是操作系统级别的线程,也就是 start()->start0()->pthread_creat();
其中pthread_creat()代表操作系统的函数
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
参数名字 参数定义 参数解释
pthread_t*thread 传出参数,调用之后会传出被创建线程的id 定义pthread_tpid
const pthread_arttr_t*attr 线程属性 一般传NULL
void(start_routine)(void*) 线程的启动后的主体函数 定义一个函数,然后传函数名即可
void*arg 主体函数的参数 没有可以传null