在 Java 中,创建多线程主要有 4 种常见方式。下面按从传统到现代的顺序说明,并附带示例代码。
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(); // 启动线程
}
}
缺点:
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();
}
}
✅ 优点:
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 {
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 | 否 | ⭐ |
| Runnable | 否 | ⭐⭐⭐ |
| Callable | 是 | ⭐⭐⭐ |
| 线程池 | 可选 | ⭐⭐⭐⭐⭐ |
如果你愿意,我也可以讲:
start() 和 run() 的区别你想深入哪一块?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。