為啥呼叫new Thread().start()方法會呼叫run()方法?

sayWhat_sayHello發表於2018-11-06

為啥呼叫new Thread().start()方法會呼叫run()方法?

我們看原始碼:

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 */
            }
        }
    }

我一開始以為原始碼會有一句呼叫run方法的程式碼,結果沒有發現。然後在方法的doc裡我們可以看見:

	/**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     * 呼叫start方法使此執行緒開始執行;Java虛擬機器呼叫此執行緒的run方法。兩個執行緒併發執行:當前執行緒(呼叫start的執行緒)和另一個執行緒(執行run方法的執行緒)
     * 多次啟動執行緒是不合法的。
     * 特別地,執行緒一旦完成,可能就不會重新啟動執行。
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start()

原因就是:

呼叫start方法使此執行緒開始執行;
Java虛擬機器呼叫此執行緒的run方法。
兩個執行緒併發執行:當前執行緒(呼叫start的執行緒)和另一個執行緒(執行run方法的執行緒)

也就是說如果直接呼叫run方法,則是當前執行緒呼叫run方法,而不是jvm去建立新執行緒呼叫。

再看看run方法:

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

這裡的target就是平時new Thread();傳遞的引數:

new Thread(Runnable target);

相關文章