1. 继承Thread类
特点:
- 直接继承
java.lang.Thread
类 - 重写
run()
方法 - 通过调用
start()
方法启动线程
优点:
- 实现简单直观
- 适合简单的线程任务
缺点:
- Java是单继承,继承Thread后不能再继承其他类
- 线程与任务绑定,不够灵活
示例代码:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
// 使用
MyThread thread = new MyThread();
thread.start();
2. 实现Runnable接口
特点:
- 实现
java.lang.Runnable
接口 - 实现
run()
方法 - 需要将Runnable实例传递给Thread对象
优点:
- 避免了单继承的限制
- 线程与任务分离,更灵活
- 适合多线程共享同一资源的情况
缺点:
- 不能直接返回执行结果
- 不能抛出受检异常
示例代码:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();
3. 实现Callable接口
特点:
- 实现
java.util.concurrent.Callable
接口 - 实现
call()
方法 - 需要配合
ExecutorService
和Future
使用 call()
方法可以有返回值和抛出异常
优点:
- 可以获取线程执行结果
- 可以抛出异常
- 适合需要返回结果或异常处理的场景
缺点:
- 使用相对复杂
- 需要线程池支持
示例代码:
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Callable result";
}
}
// 使用
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
String result = future.get(); // 获取返回结果
executor.shutdown();
对比总结
特性 | Thread | Runnable | Callable |
---|---|---|---|
继承/实现 | 继承Thread类 | 实现Runnable接口 | 实现Callable接口 |
返回值 | 无 | 无 | 有 |
异常处理 | 只能try-catch | 只能try-catch | 可以抛出 |
使用方式 | 直接start() | 需传给Thread | 需配合ExecutorService |
灵活性 | 低 | 中 | 高 |
适用场景 | 简单任务 | 资源共享任务 | 需要结果的任务 |
推荐:在大多数情况下,优先考虑实现Runnable或Callable接口,因为它们更灵活且符合面向对象的设计原则。