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

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

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 配合操作系统,底层由操作系统来分配一个原生的基础线程

posted @   ShaunY  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示