最近参加校招的面试,被问到了两次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方法当然是启动线程的方法了。