外观
Java实现多线程的方式,手写
来源:语雀原文 | 整理日期:2026-09-22
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口并配合Future与ExecutorService使用
下面我将详细介绍每种方式,并提供相应的示例代码。
1. 继承Thread类
继承Thread类并重写run()方法是实现多线程的最简单方式之一。
java
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}2. 实现Runnable接口
实现Runnable接口并将其实例传递给Thread对象。
java
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
}
}3. 实现Callable接口并配合Future与ExecutorService使用
Callable接口与Runnable接口的不同在于,Callable可以返回执行结果,并且可以抛出异常。通常与Future和ExecutorService一同使用
java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += i;
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
return sum;
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> future1 = executor.submit(new MyCallable());
Future<Integer> future2 = executor.submit(new MyCallable());
try {
System.out.println("Result of future1: " + future1.get());
System.out.println("Result of future2: " + future2.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
}小结
上述三种方式各有优缺点:
- 继承Thread类:
- 优点: 简单,直接继承Thread类即可。
- 缺点: Java只允许单继承,如果已经继承了其他类就无法再继承Thread。
- 实现Runnable接口:
- 优点: 可以避免单继承的局限性。
- 缺点: 无法直接获得执行结果。
- 实现Callable接口:
- 优点: 可以返回结果或抛出异常。
- 缺点: 需要配合Future和ExecutorService,相对复杂一些。
选择哪种方式取决于具体需求,如果需要返回结果或处理异常推荐使用Callable接口,如果只是简单的多线程操作Runnable接口足够。