比如 thread(Runable taget)
里面说,是构造一个新的方法老指定taget 的runn()方法void.run()
启动这个线程并引发调用这个run方法但是我看 jdk 源码 里面thread 类
里面 run 方法 就一个方法体 没 内容啊 怎么回事呢。
里面说,是构造一个新的方法老指定taget 的runn()方法void.run()
启动这个线程并引发调用这个run方法但是我看 jdk 源码 里面thread 类
里面 run 方法 就一个方法体 没 内容啊 怎么回事呢。
不管哪种方法,都得实现继承来的run方法。
thread(Runable taget),事实上你传进来的自定义的线程类已经实现了run方法,然后在构造真正的线程,执行线程时,调用的其实是你自己定义的那上线程类的run方法(继承自父类)。
new Thread(Runnable R);如果实现了Runnable接口的类R不为null,则在该线程启动时调用的run方法为R对象的run方法
如果R为null,该方法不执行任何操作并返回(也就是楼主所说的空方法)。
所以在继承Thread类来启动一个线程时,子类一定要重写父类的run方法,要不然就是一个空方法
public void run() {
if (target != null) {
target.run();
}
}谁说Thread类里的run方法没有代码?那个target就是你传给Thread(Runnable target)中的target。
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
可以看到是JVM调用了run方法。其实你看JDK的源代码就知道Thread类其实也实现了Runnable接口,你了使用重载的构造函数Thread(Runnable target)只是将实现了Runnable接口的类定义在外部而已。下面是run方法的文档说明
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Subclasses of Thread should override this method.
可以看到,如果使用实现了Runnable接口的对象,则执行我们自定义那个对象的run方法,否则这个方法将什么也不做,并且返回。文档明确建议Thread类的子类应该重写run方法。