在 Java 中,多线程的创建方式主要有以下几种(从常见到不常见):
Thread 类(不推荐)class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 启动线程
}
}
✅ 简单
❌ 不能继承其他类(Java 单继承)
Runnable 接口(推荐 ✅)class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
✅ 解耦任务与线程
✅ 可继承其他类
✅ 最常用
Callable + FutureTask(有返回值 ✅)import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "线程返回结果";
}
}
public class Test {
public static void main(String[] args) throws Exception {
FutureTask<String> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
System.out.println(task.get()); // 获取返回值
}
}
✅ 可返回结果
✅ 可抛出异常
❌ 写法稍复杂
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(() -> {
System.out.println("线程池执行");
});
pool.shutdown();
}
}
✅ 性能高
✅ 控制线程数量
✅ 实际项目首选
new Thread(() -> {
System.out.println("Lambda 线程");
}).start();
✅ 简洁
✅ 常用于 Runnable
| 方式 | 是否有返回值 | 是否推荐 |
|---|---|---|
| Thread | ❌ | ❌ |
| Runnable | ❌ | ✅ |
| Callable | ✅ | ✅ |
| 线程池 | ✅ | ✅✅✅ |
如果你愿意,我可以继续讲:
你想深入哪一块?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。