java中启动线程通过run方法与start放的区别

java中启动线程通过run方法与start放的区别

1.通过start方法启动线程,是真正的创建多线程,无需等待run方法里面的代码块执行完成后再执行run方法后面的代码块。此时start方法创建的线程处于就绪状态,等到得到cpu时间片后就执行run方法里面的代码块,run方法执行完成后,词线程结束。
这里写图片描述
2.通过run方法启动线程,并没有真正的创建多线程,此时还是只有一个主线程,调用run方法相当于调用类的普通方法。
这里写图片描述
3.start方法的源码:
/**java
* Causes this thread to begin execution; the Java Virtual Machine
* calls the run method of this thread.
*


* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* start method) and the other thread (which executes its
* run method).
*


* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
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 */
        }
    }
}

private native void start0();

调用start方法后首先会判断threadStatus状态是否为0.如果不为0则泡醋一场,如果正常的话,将此线程加入线程组,尝试执行start0方,start0方法是一个本地代码(其他语言编写的接口),所以调用start方法会创建新的线程。
我们再看看Thread里run()的源码:
@Override
public void run() {
if (target != null) {
target.run();
}
}

如果target不为空,则调用target的run()方法,那么target是什么:
/* What will be run. */
private Runnable target;

targt其实是一个Runable接口,所以调用他的run方法就相当于调用一个类的普通方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值