基础实现方法
继承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
构造器:
public class MyRunnable implements Runnable { @Override public void run() { System.out.println("线程执行: " + Thread.currentThread().getName()); } public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); } }
优势:
- 解耦任务与线程执行逻辑
- 支持多实现,适合资源共享场景
进阶实现方式(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)
推荐的生产环境方案:
ExecutorService pool = Executors.newFixedThreadPool(4); pool.execute(() -> { System.out.println("使用Lambda表达式提交任务"); }); pool.shutdown();
线程池的深度配置
通过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
类保证可见性
- 使用
Java提供多层次的多线程实现方案:
- 简单场景:优先选择
Runnable
接口 - 异步结果需求:使用
Callable
+Future
- 生产环境:必须配置线程池
- 高并发系统:结合锁机制与并发工具类
引用说明
本文代码示例基于Oracle官方Java 17文档规范,线程池参数设计参考《Java并发编程实战》(Brian Goetz著),实践建议融合了行业标准与生产环境验证经验。
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/6313.html