JAVA中创建线程thread.start方法

java中创建一个新的线程有多种方式,如new Thread,实现runnable,实现callball;但归根结底都是new Thread,重写run方法。

如果调用run方法,则只是使用当前线程调用了一个普通的方法,而不是new Thread执行run方法。

执行Thread.start方法的源码:


public class Thread implements Runnable {
    //本地方法,注册java方法和jvm方法的映射关系
    //比如:java中thread的sleep方法,映射的jvm中sleep方法
    private static native void registerNatives();
    static {
        registerNatives();
    }

    //thread的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()方法
            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 */
            }
        }
    }

  
    //registerNatives映射关系使用上了
    //执行jvm中的创建线程方法
    //直接交给操作系统内核去启动一个线程
    //内核线程初始化、创建线程完成后,会调用thread.run方法
    private native void start0();



}

总结:

1.new Thread时,会创建本地方法和jvm内核库方法(c++实现)的一个映射关系;

2.调用start方法时,会调用start0方法,这个方法对应jvm的一个内核库方法,执行该jvm方法;

3.jvm创建线程完成后,会使用新创建的线程回调thread.run方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值