您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,ExecutorService
用于管理和执行线程任务
Future.get()
方法捕获异常:当你提交一个任务给ExecutorService
时,它会返回一个Future
对象。你可以使用这个对象的get()
方法来获取任务的结果。如果任务在执行过程中抛出了异常,get()
方法会将其包装成一个ExecutionException
,你可以通过调用ExecutionException.getCause()
方法来获取原始异常。
示例代码:
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future = executor.submit(() -> {
// 你的任务代码,可能抛出异常
throw new RuntimeException("任务异常");
});
try {
future.get();
} catch (InterruptedException e) {
// 处理中断异常
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
// 获取原始异常
Throwable cause = e.getCause();
cause.printStackTrace();
} finally {
executor.shutdown();
}
Callable
接口:Callable
接口允许你在任务完成时返回一个结果,并且可以抛出异常。当你提交一个实现了Callable
接口的任务时,ExecutorService
会返回一个Future<T>
对象,其中T
是任务返回的结果类型。你可以使用Future.get()
方法来获取任务的结果,如果任务抛出了异常,get()
方法会将其包装成一个ExecutionException
。
示例代码:
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
// 你的任务代码,可能抛出异常
throw new RuntimeException("任务异常");
});
try {
String result = future.get();
} catch (InterruptedException e) {
// 处理中断异常
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
// 获取原始异常
Throwable cause = e.getCause();
cause.printStackTrace();
} finally {
executor.shutdown();
}
在这两种方法中,你都可以处理任务抛出的异常。你可以根据你的需求选择合适的方法来处理异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。