1.Runnable创建线程避免了单继承的局限性
一个类只能继承一个类,类继承了Thread类就不能继承其他的类
实现Runnable接口。还可以继承其他的类,实现其他的接口
2.增强了程序的扩展性,降低了程序的耦合性(解耦)
实现Runnable接口的方式,把设置线程任务和开启新线程进行了分离(解耦)
实现类中,重写了run方法:用来设置线程任务`
public class RunableImpl implements Runnable {
@Override
public void run() {
// 重写方法体:
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);//打印线程名称
}
}
}
创建Thread类对象,调用star方法:用来开启新线程
public class DemoRunable {
public static void main(String[] args) {
RunableImpl run = new RunableImpl();
Thread thread = new Thread(run);
thread.start();
}
}