Thread 是一个类,Runnable 是一个接口,下面看一下源码。
Thread 是一个类,这个类实现了 Runnable 接口
Runnable 非常简单,只有一个抽象的 run 方法,说明这个接口并没有具有多线程的特性,它是依赖 Thread 里面的 start 方法来创建子线程,再调用 Thread 里面实现好的 run 方法去执行相应的业务逻辑,从而具备多线程的特性。
如何使用 Thread 类来实现多线程,看下面的示例。
- 编写一个类继承 Thread 类 ```java package thread;
public class MyThread extends Thread { private String name;
public MyThread(String name) {this.name = name;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println("Thread start: " + this.name + ",i= " + i);}}
}
2. 编写一个类执行多线程
```java
package thread;
public class ThreadDemo {
public static void main(String[] args) {
MyThread mt1 = new MyThread("Thread1");
MyThread mt2 = new MyThread("Thread2");
MyThread mt3 = new MyThread("Thread3");
mt1.start();
mt2.start();
mt3.start();
}
}

可以看到线程是交替执行的,即线程 1 还没完成的时候,线程 2 已经执行了,已经达到多线程的目的了。
- 编写一个类,实现 Runnable 接口 ```java package thread;
public class MyRunnable implements Runnable { private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread start: " + this.name + ",i= " + i);
}
}
}
4. 编写一个类执行多线程,由于 Runnable 接口并没有 start 方法,因此需要 Thread 来执行 start 方法
```java
package thread;
public class RunnableDemo {
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable("MyRunnable1");
MyRunnable mr2 = new MyRunnable("MyRunnable2");
MyRunnable mr3 = new MyRunnable("MyRunnable3");
Thread t1 = new Thread(mr1);
Thread t2 = new Thread(mr2);
Thread t3 = new Thread(mr3);
t1.start();
t2.start();
t3.start();
}
}

可以看到 Runnable 也能实现多线程
- Thread 是实现了 Runnable 接口的类,使得 run 支持多线程
- 因类的单一继承原则,推荐使用 Runnable 接口
在开发过程中,为了提升系统的可扩展性,推荐使业务类实现 Runnable 接口,将业务逻辑封装在 run 方法里,便于后续给普通类附上多线程的特性。
