java Thread类的run()方法以及start()方法

最近参加校招的面试,被问到了两次run方法与start方法的区别,问题虽然简单,但是对于初学者来说还是比较容易混淆。

其实这些知识都没有必要刻意去记,无聊时看看源代码,了解了原理,基本一下子就会记住。这也是我学习java总结的一个

小经验吧。

好了,废话不多说了,下面进入Thread类来看看,这是Thread类中run方法的代码。

@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

其中的target为一个Runnable的实例,如下所示,

/* What will be run. */
    private Runnable target;

所以run方法中先判断构造方法中是否传入了一个Runnable的实例,是则执行Runnable中的run方法。总之,run方法中的代码是线程要执行的任务

的代码。

再来看看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 */
            }
        }
    }

可以看到,start()方法中调用了start0()方法,再来看看start0()方法。

private native void start0();

start0()方法是一个native方法,由于线程的创建需要底层的操作系统的支持,所以start方法当然是启动线程的方法了。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值