• java:CompletableFuture的简单例子


    java:CompletableFuture的简单例子

    package com.chz.myTest;
    
    import lombok.extern.slf4j.Slf4j;
    
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.CompletionStage;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    @Slf4j
    public class MyTestCompletableFutureTest
    {
        public static void main1(String[] args) throws ExecutionException, InterruptedException
        {
            Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
            String s = completableFuture.get();
            log.info(s);
        }
    
        public static void main2(String[] args) throws ExecutionException, InterruptedException
        {
            log.info("start");
            CompletableFuture<String> completableFuture = new CompletableFuture<>();
    
            new Thread(()->{
                try {
                    Thread.sleep(2000);
                    log.info("准备调用:complete()");
                    completableFuture.complete("Hello");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
    
            log.info("准备调用:completableFuture.get()");
            String s = completableFuture.get();     // 这里会被阻塞
            log.info("result: {}", s);
        }
    
        public static void main3(String[] args) throws ExecutionException, InterruptedException
        {
            log.info("start");
            CompletableFuture<String> completableFuture = new CompletableFuture<>();
    
            new Thread(()->{
                try {
                    Thread.sleep(2000);
                    log.info("准备调用:cancel()");
                    completableFuture.cancel(true);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
    
            log.info("准备调用:completableFuture.get()");
            try {
                String s = completableFuture.get();     // 这里会被阻塞
                log.info("result: {}", s);
            } catch (Exception e) {
                log.info("exception: {}, {}", e.getClass().getSimpleName(), e.getMessage(), e);
            }
        }
    
        public static void main4(String[] args) throws ExecutionException, InterruptedException
        {
            CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(()->{
                return "supplyAsync";
            });
            String s = supplyAsync.get();
            log.info("result: " + s);
        }
    
        public static void main5(String[] args) throws ExecutionException, InterruptedException
        {
            CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> "1");
            stringCompletableFuture = stringCompletableFuture.thenCompose(new Function<String, CompletionStage<String>>() {
                @Override
                public CompletionStage<String> apply(String s) {
                    log.info("s1: " + s);
                    return CompletableFuture.supplyAsync(() -> s + " 2");
                }
            });
            stringCompletableFuture = stringCompletableFuture.thenCompose(new Function<String, CompletionStage<String>>() {
                @Override
                public CompletionStage<String> apply(String s) {
                    log.info("s2: " + s);
                    return CompletableFuture.supplyAsync(() -> s + " 3");
                }
            });
            String s = stringCompletableFuture.get();
            log.info("s3: " + s);
        }
    
        public static void main6(String[] args) throws ExecutionException, InterruptedException
        {
            CompletableFuture<String> completableFuture = CompletableFuture
                    .supplyAsync(() -> "Hello")
                    .thenCombine(
                            CompletableFuture.supplyAsync(() -> " World"),
                            (s1, s2) -> s1 + s2
                    );
            String s = completableFuture.get();
            log.info(s);
        }
    
        public static void main7(String[] args)
        {
            CompletableFuture<Void> future = CompletableFuture
                    .supplyAsync(() -> "Hello")
                    .thenAcceptBoth(
                            CompletableFuture.supplyAsync(() -> " World"),
                            (s1, s2) -> {
                                log.info("result: " + (s1 + s2));
                            }
                    );
        }
    
        public static void main8(String[] args) throws InterruptedException
        {
            CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
                log.info("1");
                return "Hello";
            });
            CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
                log.info("2");
                return "Beautiful";
            });
            CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
                log.info("3");
                return "World";
            });
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3);
            voidCompletableFuture.join();
        }
    
        public static void main9(String[] args)
        {
            CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
            CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
            CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
    
            String combined = Stream.of(future1, future2, future3)
                                    .map(CompletableFuture::join)
                                    .collect(Collectors.joining(" "));
    
            log.info(combined);
        }
    
        public static void main10(String[] args) throws ExecutionException, InterruptedException
        {
            CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
                log.info("supplyAsync");
                throw new RuntimeException("Computation error!");
            });
            CompletableFuture<String> handle = completableFuture.handle((s, t) -> {
                log.info("handle");
                return (s != null) ? s : "Hello, Stranger!";
            });
            String s = handle.get();
            log.info("result: " + s);
        }
    
    }
    
  • 相关阅读:
    中医药知识图谱创建与应用辅导资料汇编
    dom4j读取xml内容时丢失换行符
    IoT 物联网 JavaScript 全栈开发,构建家居环境监控系统实战
    终于找到了!多种类型的电子期刊模板在这里!
    为什么Video Speed Manager 和 Video Speed Controller 的chrome插件对有些B站视频不能调速
    Kafka - 07 Zookeeper中存储的 Kafka 信息
    x86汇编_压缩BCD码_DAA指令_DAS指令_笔记57
    安装Joplin Server私有化部署(docker)
    多GPU训练大型模型:资源分配与优化技巧 | 英伟达将推出面向中国的改良芯片HGX H20、L20 PCIe、L2 PCIe
    RocketMQ源码(8)—Producer发送消息源码(2)—单向、同步、异步发送消息【一万字】
  • 原文地址:https://blog.csdn.net/chenhz2284/article/details/139885339