线程题总结
 · 阅读需 6 分钟
java 开启线程有哪几种方式
在 Java 中,开启线程有多种方式,主要包括以下几种:
1. 继承 Thread 类
继承 Thread 类并重写 run() 方法是最基本的线程创建方式。
示例:
class MyThread extends Thread {
    @Override
    public void run() {
        // 线程要执行的任务
        System.out.println("Thread is running...");
    }
}
public class ThreadExample {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}
- 优点:代码简单,直观。
 - 缺点:无法继承其他类,因为 Java 不支持多重继承。这样会限制类的灵活性。
 
2. 实现 Runnable 接口
实现 Runnable 接口是 Java 中推荐的线程创建方式,尤其适用于需要实现多线程功能的类已经继承了其他类的情况。Runnable 接口只包含一个方法:run()。
示例:
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程要执行的任务
        System.out.println("Runnable thread is running...");
    }
}
public class ThreadExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start(); // 启动线程
    }
}
- 优点:使用更灵活,可以实现接口并继承其他类。
 - 缺点
 
