最近參加校招的面試,被問到了兩次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方法當然是啓動線程的方法了。