异步回调CompletableFuture实现Future接口

异步回调

	Future 接口在 Java 5 中被引入,设计初衷是对将来某个时刻会发生的结果进行建模。
它建模了一种异步计算,返回一个执行运算结果的引用,当运算结束后,这个引用被返回
给调用方。在Future中触发那些潜在耗时的操作把调用线程解放出来,让它能继续执行其
他有价值的工作,不需要等待耗时的操作完成。

在这里插入图片描述

没有返回值的runAsync 异步回调

	public static void main(String[] args) {
    
    

		// (没有返回值的runAsync 异步回调)
		CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
    
    
			try {
    
    
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
    
    
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "runAsync");
		});

		System.out.println("1111");

		try {
    
    
			// 获取阻塞执行结果
			completableFuture.get();
		} catch (InterruptedException e) {
    
    
			e.printStackTrace();
		} catch (ExecutionException e) {
    
    
			e.printStackTrace();
		}
	}

有返回值的supplyAsync 异步回调 ,有成功

// (有返回值的supplyAsync 异步回调 ,有成功和失败)
	@Test
	public void test() {
    
    
		CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
    
    
			try {
    
    
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
    
    
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "runAsync");
			return 1024;
		});

		System.out.println("1111");

		try {
    
    
			completableFuture.get();
		} catch (InterruptedException e) {
    
    
			e.printStackTrace();
		} catch (ExecutionException e) {
    
    
			e.printStackTrace();
		}
	}

有返回值的supplyAsync 异步回调 ,有成功和失败

// (有返回值的supplyAsync 异步回调 ,有成功和失败)
	@Test
	public void test2() throws InterruptedException, ExecutionException {
    
    
		CompletableFuture<Integer> completableFuture =
                CompletableFuture.supplyAsync(() -> {
    
    
                    System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
                    int i = 10 / 0;
                    return 1024;
                });
        System.out.println(completableFuture.whenComplete((t, u) -> {
    
    
            System.out.println("t=>" + t); // 正常的返回结果
            System.out.println("u=>" + u); // 错误信息:java.util.concurrent.CompletionException:java.lang.ArithmeticException: /byzero
        }).exceptionally((e) -> {
    
    
            System.out.println(e.getMessage());
            return 233; // 可以获取到错误的返回结果
        }).get());
	}

猜你喜欢

转载自blog.csdn.net/jj89929665/article/details/112999775