CompletableFuture 使用指南与案例

CompletableFuture 使用指南与案例

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

一、创建异步任务

1. supplyAsync

异步执行有返回值的任务

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

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

二、异步回调

1. thenApply

转换结果

CompletableFuture 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 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 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 future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "World");

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

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

2. thenAcceptBoth

消费两个任务的结果

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

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

3. runAfterBoth

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

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

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

4. applyToEither

使用最先完成的任务结果

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

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

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

5. acceptEither

消费最先完成的任务结果

CompletableFuture fastFuture = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "Fast";
});
CompletableFuture 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 future1 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {}
    return "Hello";
});
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
    try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {}
    return "World";
});

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

7. thenCompose

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

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

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

四、多CompletableFuture联合处理

1. allOf

等待所有任务完成

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

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

CompletableFuture anyFuture = CompletableFuture.anyOf(future1, future2);

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

                            
                        
                    
                    
                    

你可能感兴趣的:(java,工具类,python,网络,服务器)