一、前言
- Runnable 和 Callable 是 Java 多线程编程中用于定义任务的接口。
二、详细区别
- 返回值
- Runnable 的 run() 方法无返回值,适合无需返回结果的任务(如日志记录)。
- Callable 的 call() 方法返回泛型值,可通过 Future.get() 获取结果(需注意此方法会阻塞主线程)。
- 异常处理
- Runnable 的 run() 方法只能通过 try-catch 内部处理异常,无法向外传递。
- Callable 的 call() 方法可抛出受检异常,外部通过 Future.get() 捕获 ExecutionException,并通过 e.getCause() 获取原始异常信息。
- 使用方式
- Runnable 可直接通过 new Thread(runnable).start() 启动,或提交至 ExecutorService。
- Callable 必须通过 ExecutorService.submit() 提交,返回 Future 对象用于管理任务状态和结果。

三、区别总结

四、示例代码
Runnable runnableTask = () -> System.out.println("Runnable任务执行");
new Thread(runnableTask).start();
Callable<String> callableTask = () -> {if (someCondition) throw new Exception("Callable异常");return "Callable任务结果";
};
Future<String> future = executorService.submit(callableTask);
String result = future.get();
五、应用场景
- Runnable:日志记录、异步通知等简单任务。
- Callable:数据库查询、文件处理等需要结果或异常监控的任务。