并发编程类CompletableFuture的使用

有返回结果的supplyAsync

此方法第二个参数需要传入一个线程池
代码案例

 private static ExecutorService pool;
public static void main(String[] args) throws Exception{
    // 初始化线程池
    pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        // 模拟一个耗时的计算
        try {
            TimeUnit.SECONDS.sleep(6);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        System.out.println("2222");
        return "Hello, CompletableFuture!";
    });
    CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
        // 模拟一个耗时的计算
        try {
            TimeUnit.SECONDS.sleep(6);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        System.out.println("555555");
        return "Hello, CompletableFuture11111!";
    });
    CompletableFuture.allOf(future, future2).join(); // 使用join方法等待所有任务执行完成
    System.out.println("33333" + future.get()); // 使用 get 方法阻塞等待结果
    System.out.println("4444" + future2.get());
    pool.shutdown();
    System.out.println("111111");
}

没有返回结果的runAsync

// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // 模拟一个耗时的操作
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    System.out.println("Task completed!");
});
future.join();

处理结果的方法thenAccept

此方法需要先调用join方法等待异步执行完成,否则可能会获取不到结果

// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> faultyFuture = CompletableFuture.supplyAsync(() -> {
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Something went wrong1111!";
}, pool);

faultyFuture.join();
faultyFuture.thenAccept(result -> {
    System.out.println("Result: " + result);
});
pool.shutdown();

使用 exceptionally 处理异常

// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> faultyFuture = CompletableFuture.supplyAsync(() -> {
    // 模拟一个耗时的操作
    try {
        TimeUnit.SECONDS.sleep(6);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    throw new RuntimeException("Something went wrong!");
}, pool);

faultyFuture.exceptionally(ex -> {
    System.err.println("Exception caught: " + ex.getMessage());
    return "Default value";
}).thenAccept(result -> {
    System.out.println("Result after handling exception: " + result);
});
pool.shutdown();

组合多个 CompletableFuture

使用 thenCompose 和 thenCombine

// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello", pool);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World", pool);

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

combinedFuture.thenAccept(result -> {
    System.out.println(result); // 输出: Hello, World
});
pool.shutdown();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值