62,614
社区成员
发帖
与我相关
我的任务
分享
/**
* 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();
}
}
可以看到,Thread.run()就是调用了target.run(),而target是啥呢?起始就是你new Thread时传过来的那个Runnable。
这时候你可能会纳闷了,Thread这个类这个run方法就是调用我传的那个Runnable的run方法= =,为什么要这么搞呢??
这就要说java线程的两种创建方式啦,第一种就是new Thread(Runnable target),实现并传进来一个runnable。关键问题来了,Java线程还有第二种创建方式,就是继承Thread类,并且覆写它的run方法。
为什么这两种方式都可以呢???
因为,调用start()后,jvm开始线程时,会在新线程里执行Thread的run方法。覆写当然可以啦,然后,如果你没覆写,传进来一个Runnable的话,Thread的run方法默认实现就是调用你这个runnable的run方法,然后就是你这个Runnable的run方法在新线程里执行了。
================
另外,值得思考的是,Thread类,也实现了Runnable接口。