Java如何创建多线程的多种方式?
- 后端开发
- 2025-05-29
- 7
基础实现方法
继承Thread类
通过继承java.lang.Thread类并重写run()方法实现:
public class MyThread extends Thread { @Override public void run() { System.out.println("线程执行: " + Thread.currentThread().getName()); } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } }
特点:
- 简单直接,适合快速验证
- 缺点:单继承限制,无法继承其他类
实现Runnable接口
更推荐的方式,实现Runnable接口并传入Thread构造器:

优势:
- 解耦任务与线程执行逻辑
- 支持多实现,适合资源共享场景
进阶实现方式(Java 5+)
实现Callable接口
需要返回结果或抛出异常时使用:
import java.util.concurrent.*; public class MyCallable implements Callable<String> { @Override public String call() throws Exception { return "执行结果来自:" + Thread.currentThread().getName(); } public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new MyCallable()); System.out.println(future.get()); // 阻塞获取结果 executor.shutdown(); } }
线程池(Executor Framework)
推荐的生产环境方案:

线程池的深度配置
通过ThreadPoolExecutor自定义线程池参数:
ThreadPoolExecutor customPool = new ThreadPoolExecutor( 2, // 核心线程数 10, // 最大线程数 60L, TimeUnit.SECONDS, // 空闲线程存活时间 new LinkedBlockingQueue<>(100) // 任务队列 );
参数解析:
- corePoolSize:长期保留的线程数量
- maximumPoolSize:队列满时允许创建的最大线程数
- keepAliveTime:非核心线程空闲存活时间
- workQueue:任务缓存队列(推荐有界队列)
最佳实践与注意事项
-
资源管理

- 使用try-with-resources或finally块确保线程池关闭
- 避免new Thread().start()的裸用方式
-
异常处理
- 为线程设置UncaughtExceptionHandler
- 在Runnable实现中捕获所有异常
-
性能优化
- 根据任务类型选择线程池类型:
- newCachedThreadPool:短生命周期任务
- newFixedThreadPool:CPU密集型任务
- newScheduledThreadPool:定时任务
-
并发安全
- 使用ConcurrentHashMap等线程安全集合
- 通过volatile或Atomic类保证可见性
- 简单场景:优先选择Runnable接口
- 异步结果需求:使用Callable+Future
- 生产环境:必须配置线程池
- 高并发系统:结合锁机制与并发工具类
Java提供多层次的多线程实现方案:
引用说明
本文代码示例基于Oracle官方Java 17文档规范,线程池参数设计参考《Java并发编程实战》(Brian Goetz著),实践建议融合了行业标准与生产环境验证经验。
- 根据任务类型选择线程池类型: