代码:
CompletableFuture.supplyAsync(() -> {
// 异步调用的逻辑
}).exceptionally(ex -> {
System.out.println("异步调用失败:" + ex.getMessage());
return null;
});
代码:
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> future = executor.submit(() -> {
// 异步调用的逻辑
});
try {
future.get(1, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
System.out.println("异步调用失败:" + e.getMessage());
}
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<String> future = executor.submit(() -> {
// 异步线程执行的代码
return "success";
});
try {
String result = future.get();
// 处理异步线程的执行结果
} catch (InterruptedException | ExecutionException e) {
// 异常处理逻辑
e.printStackTrace();
}