栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

CompletableFuture用法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

CompletableFuture用法

一、是什么
是Java 8 新增加的Api,该类实现,Future和CompletionStage两个接口,提供了非常强大的Future的扩展功能,可以通过回调的方式处理计算结果
二、怎么用 1、创建异步任务:
public static void main(String[] args) throws Exception {
         ExecutorService executor = Executors.newFixedThreadPool(10);
         String SUCCESS = "success";
        
        CompletableFuture runAsyncFuture = CompletableFuture.runAsync(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finish");
        });
        System.out.println("runAsync方式,未指定线程池------》"+ runAsyncFuture.get());

        System.out.println();

        
        CompletableFuture runAsyncFutureWithExecutor = CompletableFuture.runAsync(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finish");
        }, executor);
        System.out.println("runAsync方式,指定了线程池------》"+runAsyncFutureWithExecutor.get());

        System.out.println();

        
        CompletableFuture supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finish");
            return SUCCESS;
        });
        System.out.println("supplyAsync方式,未指定线程池------》"+supplyAsyncFuture.get());

        System.out.println();


        
        CompletableFuture supplyAsyncFutureWithExecutor = CompletableFuture.supplyAsync(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finish");
            return SUCCESS;
        }, executor);
        System.out.println("supplyAsync方式,指定了线程池------》"+supplyAsyncFutureWithExecutor.get());

        executor.shutdown();
    }
2、异步回调 thenApply:
        CompletableFuture future = CompletableFuture.supplyAsync(()-> {
                long result = new Random().nextInt(100);
                System.out.println("result1=" + result);
                return result;
        }).thenApply(t-> {
                long result = t * 5;
                System.out.println("result2=" + result);
                return result;
        });
        long result = future.get();
        System.out.println(result);
thenAccept:
        CompletableFuture future = CompletableFuture.supplyAsync(() ->{
                int num= new Random().nextInt(10);
                return num;

        }).thenAccept(integer -> {
            System.out.println(integer);
        });
        future.get();
thenRun:
        CompletableFuture future = CompletableFuture.supplyAsync(()-> {
            int num= new Random().nextInt(10);
            return num;
        }).thenRun(() -> {
            System.out.println("thenRun ...");
        });
        future.get();
3、组合处理 runAfterBoth:

        CompletableFuture
                .supplyAsync(() -> {
                    System.out.println(10);
                    return 10;
                })
                .runAfterBoth(CompletableFuture.supplyAsync(() -> {
                    System.out.println(20);
                    return 20;
                }), () -> System.out.println("开始运行run"));
thenAcceptBoth:

        CompletableFuture future1 = CompletableFuture.supplyAsync(() ->{
                String s="hujunxian";
                return s;
        });

        CompletableFuture future2 = CompletableFuture.supplyAsync(() ->{
                String s1="2021";
                return s1;
        });

        future2.thenAcceptBoth(future1, (s1,s) ->{
                System.out.println(s1 + " , " + s);
        });
thenCombine:
        CompletableFuture future1 = CompletableFuture.supplyAsync(() ->{
                String s="hello";
                return s;
        });
        CompletableFuture future2 = CompletableFuture.supplyAsync(()-> {
                String ss="hello";
                return ss;
        });
        CompletableFuture result = future1.thenCombine(future2, (t,u) ->{
                String res=t+" , "+u;
                return res;
        });
        System.out.println(result.get());
runAfterEither:
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("s1");
            return "s1";
        }).runAfterEither(CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("s2");
            return "s2";
        }), () -> System.out.println("hello world")).get();
acceptEither:
        Random random = new Random();
        CompletableFuture
                .supplyAsync(() -> {
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "A";
                })
                .acceptEither(CompletableFuture.supplyAsync(() -> {
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "B";
                }), System.out::println)
                .get();
applyToEither:

        String result = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "s1";
        }).applyToEither(CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello world";
        }), s -> s).join();
        System.out.println(result);
allOf/anyOf:
allOf是多个任务都执行完成后才会执行后面的操作;anyOf是多个任务只要其中一个执行完成就会执行后面的操作
        Random random = new Random();
        CompletableFuture.anyOf(
//        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> {
                    int a=random.nextInt(5000);
                    try {
                        Thread.sleep(random.nextInt(5000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(a);
                }),
                CompletableFuture.runAsync(() -> {
                    int b=random.nextInt(5000);
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(b);
                })).thenRun(()-> System.out.println("allOf")).get();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/332818.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号