知乎专栏 |
@Service public class DemoAsyncServiceImpl implements DemoAsyncService { public static Random random =new Random(); @Async("OneAsync") public Future<String> doTaskOne() throws Exception { System.out.println("开始做任务一"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务一完成"); } @Async("TwoAsync") public Future<String> doTaskTwo() throws Exception { System.out.println("开始做任务二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务二完成"); } @Async public Future<String> doTaskThree() throws Exception { System.out.println("开始做任务三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务三完成"); } }
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { throw new RuntimeException(); // return "程序出现异常"; }).exceptionally((e) -> { System.out.println("程序出现异常"); return "程序出现异常"; }); System.out.println(completableFuture.get());
@Service public class MyService { @Async public CompletableFuture<String> asyncMethod() { try { // 异步方法逻辑... return CompletableFuture.completedFuture("Success"); } catch (Exception e) { // 处理异常... return CompletableFuture.failedFuture(e); } } } // 调用异步方法并处理异常 CompletableFuture<String> future = myService.asyncMethod(); future.exceptionally(e -> { // 异常处理逻辑... return "Error"; });
@GetMapping("/completableFutureExceptionally") public String completableFutureExceptionally() throws ExecutionException, InterruptedException { CompletableFuture.supplyAsync(() -> { System.out.println("当前线程名称:" + Thread.currentThread().getName()); throw new RuntimeException(); }).exceptionally((e) -> { System.out.println(e.getMessage()); return "程序出现异常"; }); return "Done"; }
输出结果
当前线程名称:ForkJoinPool.commonPool-worker-1 java.lang.RuntimeException