示例
public class MyRunnable implements Runnable{
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name);
}
}
public class MyThread extends Thread{
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name);
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable("Runnable");
MyThread myThread = new MyThread("MyThread");
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
输出结果
MyThread
Runnable
关系
- Thread是实现了Runnable接口的类,使得run支持多线程
- 因为单一继承原则,推荐多使用Runnable接口