• 从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) {
    1. T1 t1 = new T1();
    2. T2 t2 = new T2();
    3. Thread thread1 = new Thread(t1);
    4. Thread thread2 = new Thread(t2);
    5. thread1.start();
    6. thread2.start();
    } }

class T1 implements Runnable { int count = 0;

  1. @Override
  2. public void run() {
  3. while (true) {
  4. System.out.println("Hello! " + (++count));
  5. try {
  6. Thread.sleep(1000);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. if (count == 5) {
  11. break;
  12. }
  13. }
  14. }

}

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; } } } } ``` image.png