CompletableFuture 使用指南与案例

CompletableFuture 使用指南与案例

一、创建异步任务
supplyAsync
runAsync
二、异步回调
thenApply
thenAccept
thenRun
exceptionally
whenComplete
handle
三、联合处理
双CompletableFuture联合处理
thenCombine
thenAcceptBoth
runAfterBoth
applyToEither
acceptEither
runAfterEither
thenCompose
四、多CompletableFuture联合处理
allOf
anyOf

一、创建异步任务

1. supplyAsync

异步执行有返回值的任务

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Hello";
});

System.out.println(future.get()); // 输出: Hello

2. runAsync

异步执行无返回值的任务

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    System.out.println("任务完成");
});

future.get(); // 等待任务完成

二、异步回调

1. thenApply

转换结果

CompletableFuture<String> welcomeFuture = CompletableFuture.supplyAsync(() -> {
    return "World";
}).thenApply(name -> {
    return "Hello " + name;
});

System.out.println(welcomeFuture.get()); // 输出: Hello World

2. thenAccept

消费结果

CompletableFuture.supplyAsync(() -> {
    return "World";
}).thenAccept(name -> {
    System.out.println("Hello " + name); // 输出: Hello World
}).get();

3. thenRun

不消费结果,执行后续操作

CompletableFuture.supplyAsync(() -> {
    return "World";
}).thenRun(() -> {
    System.out.println("任务完成"); // 输出: 任务完成
}).get();

4. exceptionally

异常处理

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) throw new RuntimeException("出错了!");
    return "Success";
}).exceptionally(ex -> {
    System.out.println("异常: " + ex.getMessage()); // 输出: 异常: java.lang.RuntimeException: 出错了!
    return "Fallback";
});

System.out.println(future.get()); // 输出: Fallback

5. whenComplete

无论成功或异常都会执行

CompletableFuture.supplyAsync(() -> {
    return "Success";
}).whenComplete((res, ex) -> {
    if (ex != null) {
        System.out.println("异常: " + ex.getMessage());
    } else {
        System.out.println("结果: " + res); // 输出: 结果: Success
    }
}).get();

6. handle

无论成功或异常都会执行并可返回新结果

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    return "Success";
}).handle((res, ex) -> {
    if (ex != null) {
        return "Fallback";
    }
    return res + " handled";
});

System.out.println(future.get()); // 输出: Success handled

三、双CompletableFuture联合处理

1. thenCombine

合并两个独立任务的结果

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (res1, res2) -> res1 + " " + res2);

System.out.println(combinedFuture.get()); // 输出: Hello World

2. thenAcceptBoth

消费两个任务的结果

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

future1.thenAcceptBoth(future2, (res1, res2) -> {
    System.out.println(res1 + " " + res2); // 输出: Hello World
}).get();

3. runAfterBoth

两个任务都完成后执行操作

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

future1.runAfterBoth(future2, () -> {
    System.out.println("两个任务都完成了"); // 输出: 两个任务都完成了
}).get();

4. applyToEither

使用最先完成的任务结果

CompletableFuture<String> fastFuture = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "Fast";
});
CompletableFuture<String> slowFuture = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {}
    return "Slow";
});

CompletableFuture<String> resultFuture = fastFuture.applyToEither(slowFuture, res -> res + " wins");

System.out.println(resultFuture.get()); // 输出: Fast wins

5. acceptEither

消费最先完成的任务结果

CompletableFuture<String> fastFuture = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "Fast";
});
CompletableFuture<String> slowFuture = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {}
    return "Slow";
});

fastFuture.acceptEither(slowFuture, res -> {
    System.out.println(res + " wins"); // 输出: Fast wins
}).get();

6. runAfterEither

任一任务完成后执行操作

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "Hello";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {}
    return "World";
});

future1.runAfterEither(future2, () -> {
    System.out.println("有一个任务完成了"); // 输出: 有一个任务完成了
}).get();

7. thenCompose

将前一个任务的返回结果作为下一个任务的输入

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(res -> CompletableFuture.supplyAsync(() -> res + " World"));

System.out.println(future.get()); // 输出: Hello World

四、多CompletableFuture联合处理

1. allOf

等待所有任务完成

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "!");

CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);

allFutures.thenRun(() -> {
    System.out.println("所有任务完成");
    try {
        System.out.println(future1.get() + " " + future2.get() + future3.get()); // 输出: Hello World!
    } catch (Exception e) {
        e.printStackTrace();
    }
}).get();

2. anyOf

等待任一任务完成

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {}
    return "Hello";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "World";
});

CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);

System.out.println(anyFuture.get()); // 输出: World
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值