结论
- Thread.run方法会直接调用传入的Runnable对象的run方法,也就是说此时的Thread相当于一个静态代理,从而并没有通过创建一个线程的方式去执行run方法,方法的执行还是在原来的线程。
- 通过Thread.start()方法去执行时,会调用本地方法start0()去创建一个线程,此时采用动态代理的方式去调用传入的Runnable的run方法,即通过创建一个线程的方式去执行任务。
源码
Thread的run方法:
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
//调用target的run方法,没有创建线程。target就是传入的Runnable
target.run();
}
}
Thread的start()方法
/**
* 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.
*
* @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 {
//调用本地方法去创建一个线程,通过动态代理去执行Runnable的run方法
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();
也即是说,传入的Runnable的run方法会被Thread代理到自己的run方法中,并在本地方法start0()中通过动态代理调用,Thread中run方法意义也在于此。
测试
创建一个类实现Runnable:
分别用两种方式执行:
run()方式
结果:
可以看到是Cat先睡醒,再打印嘿嘿,所以是串行执行的,也就是一个线程执行
start方式:
结果:
Cat还没睡醒就结束了,说明开启了一个线程执行Cat的run方法,但是在它睡觉的时候主线程结束了,因此等不到Cat睡醒。