当前位置: 首页 > news >正文

并发--Callable vs Runnable

核心对比总表(Callable vs Runnable)

维度RunnableCallable
接口定义public interface Runnablepublic interface Callable<V>
核心方法void run()V call() throws Exception
返回值❌ 无返回值✅ 可返回泛型结果
异常处理❌ 只能处理非受检异常✅ 可抛出任意受检/非受检异常
执行方式Thread/Executor.execute()ExecutorService.submit()[也可以通过Thread执行,一般不用]
适用场景简单异步任务需要结果/异常处理的复杂任务

1. 接口定义与核心方法

Runnable(Java 1.0引入)

@FunctionalInterface
public interface Runnable {// 无参数、无返回值、无异常声明void run();
}

使用示例:

Runnable printTask = () -> {System.out.println("执行Runnable任务");// 不能返回结果,不能抛出受检异常
};// 执行方式
new Thread(printTask).start();
// 或
executor.execute(printTask);

Callable(Java 5引入)

public interface Callable<V> {// 返回泛型结果,可抛出任何异常V call() throws Exception;
}

使用示例:

Callable<Integer> calcTask = () -> {System.out.println("执行Callable任务");if (Math.random() > 0.8) {throw new IOException("模拟IO异常");}return 42; // 返回计算结果
};// 执行方式
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(calcTask);//使用Thread也可以,但是Callable不推荐用
FutureTask<Integer> future = new FutureTask(calcTask);
Thread t = new Thread(future);
Integer integer = future.get(); //可以获取到calcTask 返回的结果【42】

2. 异常处理机制对比

Runnable的异常困境

Runnable fileTask = () -> {try {Files.copy(source, target); // 可能抛出IOException} catch (IOException e) {// 只能转为非受检异常throw new RuntimeException(e);}
};// 未捕获异常会导致线程终止
Thread t = new Thread(fileTask);
//使用 Thread.setUncaughtExceptionHandler为线程设置异常处理器,当线程因未捕获的异常终止时会触发该处理器。
//不用Thread.setUncaughtExceptionHandler 线程x就会报错
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println("捕获到异常: " + e.getMessage());// 可以在这里记录日志、通知其他组件等}
});
t.start();

Callable的完整异常链

Callable<String> dbTask = () -> {if (dbConnection.isClosed()) {throw new SQLException("数据库未连接");}return fetchData();
};Future<String> future = executor.submit(dbTask);try {String data = future.get();process(data);
} catch (ExecutionException e) {Throwable cause = e.getCause(); // 获取原始异常if (cause instanceof SQLException) {reconnectDatabase();}
}
http://www.dtcms.com/a/276596.html

相关文章:

  • 深入理解 Boost.Asio 中的异步核心 boost::asio::io_context
  • AI智能体|扣子(Coze)搭建【裸眼3D著名故事动画视频】工作流
  • NOIP普及组|2005T1淘淘摘苹果
  • 常用控件QWidget
  • 部署Harbor私有仓库
  • 第五章 RAG知识库进阶
  • Java项目2——增强版飞机大战游戏
  • Linux:信号
  • Redis持久化机制:RDB和AOF
  • 【面试八股文】2025最新软件测试面试
  • 多模态数据解压-Parquet
  • 【数据结构初阶】--顺序表(三)
  • 咨询导览,AI发展趋势
  • 三维点云Transformer局部感受野构建:理论、方法与挑战
  • 【图像处理基石】如何入门大规模三维重建?
  • 宁德时代2025年社招入职Verify测评语言理解数字推理考点及SHL测评真题整理
  • Augmented Nested Arrays With Enhanced DOF and Reduced Mutual Coupling
  • C++面试问题集锦
  • Linux系统编程——目录 IO
  • C++ 算法题常用函数大全
  • 独立开发第二周:构建、执行、规划
  • 数智管理学(三十二)
  • ATE-市场现状及趋势
  • AI:机器人行业发展现状
  • 用 Jpom 10 分钟搭好一套轻量级 CICD + 运维平台
  • 傅里叶方法求解偏微分方程2
  • 【C/C++】迈出编译第一步——预处理
  • 并查集理论以及实现
  • QILSTE/旗光 H6-108QHR
  • SSM项目上传文件的方式及代码