Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

37.4. 带有返回值的异步任务

37.4.1. Future

        
@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<>("任务三完成");
	}

}
        
			
			
			
			
			

37.4.2. CompletableFuture

			
        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