线程的实现方式
多线程是提高程序性能和响应速度的重要手段,Java 中有多种实现方式
- 继承 Thread 类
- 实现 Runnable 接口
- 使用 Callable 和 Future
- 使用线程池
方式一:继承 Thread 类
- 介绍:通过继承 Thread 类来实现多线程。
- 示例代码:展示如何继承 Thread 类并重写 run() 方法。
- 优点:实现简单,易于理解。
- 缺点:无法继承其他类,因为 Java 不支持多重继承。
class MyThread extends Thread {
public void run() {
// 执行需要的代码
}
}
MyThread thread = new MyThread();
thread.start();
方式二: 实现 Runnable 接口
- 介绍:通过实现 Runnable 接口来实现多线程。
- 示例代码:展示如何实现 Runnable 接口并重写 run() 方法。
- 优点:可以继承其他类,因为 Java 支持实现多个接口。
- 缺点:需要创建 Thread 对象来启动线程。
- 步骤:
- 自定义线程类实现Runnable接口
- 实现run()方法,编写线程体
- 创建线程对象,调用start()方法启动线程(启动后不一定立即执行,抢到CPU资源才能执行)
class MyRunnable implements Runnable {
public void run() {
// 执行需要的代码
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
方式三:使用 Callable 和 Future
- 介绍:通过使用 Callable 和 Future 接口来实现多线程。
- 示例代码:展示如何使用 Callable 和 Future 接口来创建和启动线程。
- 优点:可以获取线程执行的返回值。
- 缺点:相比于前两种方式,实现稍微复杂一些。
- 步骤:
- 实现Callable接口,先要返回值类型
- 重写call()方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executor.newFixedThreadPool(1);
- 提交执行:Future res = ser.submit(t1);
- 获取结果:boolean r1 = res.get();
- 关闭服务:ser.shutdownNow();
import java.util.concurrent.*;
// 自定义线程对象,实现Callable接口,重写call()方法
public class MyThread implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
// 线程执行体
for (int i = 0; i < 10; i++) {
System.out.println("我是自定义" + Thread.currentThread().getName() + "--" + i);
}
return true;
}
public static void main(String[] args) throws ExecutionException,
InterruptedException {
// main线程,主线程
// 创建线程实现类对象
MyThread thread = new MyThread();
MyThread thread2 = new MyThread();
// 创建执行服务,参数是线程池线程数量
ExecutorService ser = Executors.newFixedThreadPool(2);
// 提交执行
Future<Boolean> res = ser.submit(thread);
Future<Boolean> res2 = ser.submit(thread2);
// 获取结果
boolean r1 = res.get();
boolean r2 = res2.get();
// 关闭服务
ser.shutdownNow();
}
}
方式四:使用线程池
- 介绍:通过使用线程池来实现多线程。
- 示例代码:展示如何使用 Executor 和 ExecutorService 接口来创建和管理线程池。
- 优点:可以重用线程,避免了频繁创建和销毁线程的开销。
- 缺点:需要对线程池的大小进行合理配置,否则可能会导致性能问题
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {
public void run() {
// 执行需要的代码
}
});
鸣谢
[1] https://blog.csdn.net/qq_20957669/article/details/131201017