- 从java的设计来看,通过继承Thread或者实现Runnable接口来创建线程本质上没有区别,从jdk帮助文档我们可以看到Thread类本身就实现了Runnable接口
- 实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制,建议使用Runnable
案例:
需求:
请编写一个程序,创建两个线程,一个线程每隔1秒输出Hello!”,输出5次,退出,一个线程每隔1秒输出“WTY2002”,输出5次退出. ```java package test;
/**
- main线程启动两个子线程
*/
public class Main {
public static void main(String[] args) {
} }T1 t1 = new T1();
T2 t2 = new T2();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();
thread2.start();
class T1 implements Runnable { int count = 0;
@Override
public void run() {
while (true) {
System.out.println("Hello! " + (++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 5) {
break;
}
}
}
}
class T2 implements Runnable { int count = 0; @Override public void run() { while (true) { System.out.println(“WTY “ + (++count)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (count == 5) { break; } } } } ```