Java 多线程CompletableFuture 总结

本文详细介绍了Java中如何使用Future和CompletableFuture以及不同类型的线程池(如ExecutorService和ForkJoinPool)来执行异步任务,包括有返回值和无返回值的情况,并探讨了thenRun,thenAccept和thenApply回调方法的区别。
摘要由CSDN通过智能技术生成
//异步带有返回值
    public void asynLogin() {
        //创建线程池、通过线程submit回调callable,将值返回给Future中, Future通过get()方法读取结果集(此方法阻塞调用,在线程获取结果之前get方法会一直阻塞)
        //原生方式创建线程池
        ExecutorService executor = new ThreadPoolExecutor(5, 5, 100, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        try {
           /*
            //以下方式均可通过 new ThreadPoolExecutor 进行实现
            //newFixedThreadPool 创建线程
            ExecutorService service = Executors.newFixedThreadPool(5);
            //创建缓存类线程池:默认六十秒自动回收
            Executors.newCachedThreadPool();
            //创建单例线程池:最大线程数和线程池创建时默认为1,使用完成后回收
            Executors.newSingleThreadExecutor();*/
            Future<Map<String, Object>> mapFuture = executor.submit(new Callable<Map<String, Object>>() {
                @Override
                public Map<String, Object> call() throws Exception {
                    Map<String, Object> roleMap = new HashMap<String, Object>();
                    roleMap.put("role", "管理员");
                    long endTime = System.currentTimeMillis();
                    log.info("查询用户角色信息耗时:" + (endTime - startTime) + "毫秒");
                    return roleMap;
                }
            });
            //阻塞线程,等待结果
            mapFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //有返回值,使用内置线程池ForkJoinPool.commonPool()
        CompletableFuture<Map<String, Object>> rote = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> roleMap = new HashMap<String, Object>();
            roleMap.put("role", "管理员");
            long endTime = System.currentTimeMillis();
            log.info("查询用户角色信息耗时:" + (endTime - startTime) + "毫秒");
            return roleMap;
        });
        rote.join();

        //有返回值,使用自定义线程池
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> roleMap = new HashMap<String, Object>();
            roleMap.put("role", "管理员");
            long endTime = System.currentTimeMillis();
            log.info("查询用户角色信息耗时:" + (endTime - startTime) + "毫秒");
            return roleMap;
        }, executor);

        //没有返回值,使用内置线程ForkJoinPool.commonPool()
        CompletableFuture.runAsync(() -> {
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("执行金额增删改操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
        }).join();

        //没有返回值,使用自定义线程池
        CompletableFuture<Void> roleCompletableFuture = CompletableFuture.runAsync(() -> {
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("执行角色增删改操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
        }, executor);
        //get()和join()效果相同,join直接抛出异常,get需进行try/catch
        roleCompletableFuture.join();
//        roleCompletableFuture.get();
    }
	//thenXXX 和 thenXXXAsync 两者的区别:前者与第一个任务共用一个线程,后者使用ForkJoin线程池

    //异步任务回调:thenRun 做完第一个任务后,再做第二个任务。某个任务执行完成后,执行回调方法;但是前后两个任务没有参数传递,第二个任务也没有返回值。
    public void thenRun(){
        CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("执行金额增删改操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
        });
        CompletableFuture completableFuture1 = completableFuture.thenRunAsync(()->{
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("执行金额增删改操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
        });
        completableFuture1.join();
    }
 //异步任务回调:thenAccept 做完第一个任务后,再做第二个任务。某个任务执行完成后,执行回调方法;将第一个任务的值作为第二个任务的入参,回调方法无返回值
    public void thenAccept(){
        CompletableFuture<Map> completableFuture = CompletableFuture.supplyAsync(()->{
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> amountMap = new HashMap<String, Object>();
            amountMap.put("amount", 90);
            log.info("执行金额查询操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            return amountMap;
        });
        CompletableFuture completableFuture1 = completableFuture.thenAcceptAsync((map)->{
            long startTime = System.currentTimeMillis();
            if (Integer.parseInt(map.get("amount").toString()) > 90) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("金额充足,可以购买!:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            } else {
                log.info("金额不足,无法购买!:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            }
        });
        completableFuture1.join();
    }
//异步任务回调:thenApply 做完第一个任务后,再做第二个任务。某个任务执行完成后,执行回调方法;将第一个任务的值作为第二个任务的入参,回调方法 有 返回值
    public void thenApply(){
        CompletableFuture<Map> completableFuture = CompletableFuture.supplyAsync(()->{
            long startTime = System.currentTimeMillis();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> amountMap = new HashMap<String, Object>();
            amountMap.put("amount", 90);
            log.info("执行金额查询操作用时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            return amountMap;
        });
        CompletableFuture<Map> completableFuture1 = completableFuture.thenApply(map -> {
            long startTime = System.currentTimeMillis();
            Map<String, Object> numberMap = null;
            if (Integer.parseInt(map.get("amount").toString()) > 90) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                numberMap = new HashMap<String, Object>();
                numberMap.put("number", 90);
                log.info("金额充足,可以购买!:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            } else {
                log.info("金额不足,无法购买!:" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
            }
            return numberMap;
        });
        completableFuture1.join();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值