题目
Java中如何创建并启动一个新线程?请列举两种常见方式
信息
- 类型:问答
- 难度:⭐
考点
线程创建, Runnable接口, Thread类
快速回答
Java中创建线程的两种主要方式:
- 继承Thread类:重写run()方法,创建实例后调用start()启动
- 实现Runnable接口:实现run()方法,将实例传入Thread构造函数后调用start()启动
推荐使用实现Runnable接口的方式,更符合面向对象设计原则。
解析
1. 原理说明
Java线程创建的核心是定义线程执行的任务逻辑(run()方法),并通过Thread类启动线程。JVM会调用run()方法在独立线程中执行代码。
2. 两种实现方式及代码示例
方式一:继承Thread类
// 1. 继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行: " + Thread.currentThread().getName());
}
}
// 创建并启动线程
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动新线程
}
}方式二:实现Runnable接口
// 2. 实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行: " + Thread.currentThread().getName());
}
}
// 创建并启动线程
public class Main {
public static void main(String[] args) {
MyRunnable task = new MyRunnable();
Thread thread = new Thread(task); // 传入Runnable实例
thread.start(); // 启动新线程
}
}3. 两种方式的区别
| 对比项 | 继承Thread | 实现Runnable |
|---|---|---|
| Java继承机制 | 占用继承名额(单继承限制) | 可继承其他类,更灵活 |
| 代码耦合度 | 线程与任务强耦合 | 线程与任务解耦 |
| 资源共享 | 多个线程需创建不同实例 | 同一Runnable可被多个线程共享 |
4. 最佳实践
- 优先选择Runnable接口:避免继承限制,更符合面向对象设计
- 使用Lambda简化代码(Java 8+):
new Thread(() -> System.out.println("Lambda线程")).start(); - 不要直接调用run()方法:这会在当前线程执行而非启动新线程
5. 常见错误
- 错误启动线程:调用
run()而非start(),导致代码在当前线程执行 - 多次启动线程:对同一Thread实例重复调用
start()会抛出IllegalThreadStateException - 资源竞争问题:多个线程共享数据时未使用同步机制
6. 扩展知识
- Callable/Future:需要返回结果时使用Callable接口
- 线程池(ExecutorService):实际开发中推荐使用线程池管理线程
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> { /* 任务代码 */ }); - 线程状态:新建(NEW)、可运行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、超时等待(TIMED_WAITING)、终止(TERMINATED)