start线程开启(C源码分析)

发布时间 2023-03-27 11:19:01作者: ShaunY

一个线程开启都经历了什么

public class ThreadBaseDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
        }, "t1");
        t1.start();
    }
}
  • start 源码

    start 被 synchronized 修饰,必须全部执行完

    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 */
            }
        }
    }
    
  • start0 方法

    java 线程是通过 start 的方法启动执行的,主要内容在 native 方法 start0 中,openjdk 的写 JNl^(Java Native Interface,Java本地接口)^ 一般是一一对应的,Thread.java 对应的就是 Thread.c

    start0 其实就是 JVM_StartThread。此时查看源代码可以看到在 jvm.h 中找到了声明,jvm.cpp 中有实现。

    private native void start0();
    

    start0 的执行流程一般如下所示

    image

    • thread.c 部分

      image

    • jvm.cpp

      image
      image

    • thread.cpp

      image

    从上面三部分内容来看,一个线程的启动是由 jvm 配合操作系统,底层由操作系统来分配一个原生的基础线程