一、创建线程的方式
1、继承Thread类,覆盖run方法
2、实现Runnable接口,创建Thread类的实例,通过构造方法实现
3、Runnable接口只有一个抽象的run方法,也就是说Runnable接口本身不支持多线程
public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
4、Runnable接口多线程的实现查看Thread类的源代码,可以看到很多构造函数的参数是Runnable类或者Runnable的子类,即通过Thread类的构造方法类启动Runnable接口实现多线程
/** * Allocates a new {@code Thread} object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * {@code (null, target, gname)}, where {@code gname} is a newly generated * name. Automatically generated names are of the form * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. * * @param target * the object whose {@code run} method is invoked when this thread * is started. If {@code null}, this classes {@code run} method does * nothing. */ public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); }
5、Runnable接口的优势
- 避免单继承的局限,一个类可以继承多个接口。
- 适合于资源的共享
6、Thread类是Runnable接口的一个实现子类