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方法就相当于调用一个类的普通方法。

猜你喜欢

转载自blog.csdn.net/weixin_42925196/article/details/81865950