多线程Thread源码分析

 源码分析

	//start方法才是启动一个线程 run()是同步执行一次
	new Test0().start(); 
	//来到Thread类里面
    //查看当前线程状态是否为0
    public synchronized void start() {
//这个threadStatus为线程的状态码不为0时,当该线程已经起来了则抛出非法线程状态异常
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        //将前线程加入到线程组
        group.add(this);

        boolean started = false;
        try {
            //调用start0()方法,启动线程
            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 */
            }
        }
    }
	//接下来发现是native方法
    private native void start0();

启动线程

start0()方法

  private native void start0();

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

native方法 

native方法,该方法是jvm底层调用的,执行传入的Thread的run()方法。启动线程。至此创建线程完成。

上面的native方法,最终调用到JVM thread.cpp中,然后JVM 根据不同的操作系统会调用的对应OS create一个线程,并且该方法会告诉CPU start了一个线程,然后在cpu调度算法中执行此线程时会回调到JVM中,最终调用thread 中的run方法,也就是我们手写的代码,线程开始执行
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值