在 Java 中,创建多线程主要有 4 种常见方式。下面从最常用到不常用逐步说明,并附示例代码。
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(); // 启动线程
}
}
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 + Future(有返回值)import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "线程执行完成:" + Thread.currentThread().getName();
}
}
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<String> future = pool.submit(new MyCallable());
System.out.println(future.get()); // 获取返回值
pool.shutdown();
}
}
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
pool.execute(() -> {
System.out.println("线程:" + Thread.currentThread().getName());
});
}
pool.shutdown();
}
}
new Thread(() -> {
System.out.println("Lambda 线程");
}).start();
✅ 正确:
thread.start(); // 启动新线程
❌ 错误:
thread.run(); // 只是普通方法调用
| 方式 | 是否有返回值 | 推荐程度 |
|---|---|---|
| Thread | 否 | ⭐ |
| Runnable | 否 | ⭐⭐⭐ |
| Callable | ✅ | ⭐⭐⭐ |
| 线程池 | ✅ | ⭐⭐⭐⭐⭐ |
start() 和 run() 的区别?如果你愿意,我可以 结合面试角度 或 模拟一个真实业务场景 再详细讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。