Avatar ·

在Java中:implements Runnable 与 extends Thread — 创建线程该选哪个?

大家好!我开始学习Java中的多线程,对两种创建线程的方法感到困惑。到处都说可以继承Thread类或实现Runnable接口。但什么时候用哪个呢? 以下是我尝试过的示例: 1) extends Thread: ```java class MyThread extends Thread { public void run() { System.out.println("线程正在运行"); } } public class Main { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } } ``` 2) implements Runnable: ```java class MyRunnable implements Runnable { public void run() { System.out.println("线程正在运行"); } } public class Main { public static void main(String[] args) { MyRunnable task = new MyRunnable(); Thread t = new Thread(task); t.start(); } } ``` 两种方法都有效——我验证过了。但区别在哪里?为什么教材中建议使用Runnable?并且可以