CompletableFuture的学习

/**
 * @author gongshengjing
 * @date 2022/08/26 17:25
 * @description CompletableFuture的学习
 */
public class ThreadTest {
    public static ExecutorService service = Executors.newFixedThreadPool(10);

    /**
     * 凡是方法后缀加Async,就是新开一个线程,否则还是共用一个线程,比如whenComplete和whenCompleteAsync
     */

    @SneakyThrows
    public static void main(String[] args) {
        System.out.println("------------------------------------------------------------------------");
        /**
         * CompletableFuture  supplyAsync携带返回值,runAsync没有返回值
         * whenComplete  exceptionally的使用
         */
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, service).whenComplete((result,exception)->{
            //虽然能得到异常信息,但是没法修改返回数据
            System.out.println(String.format("异步任务完成了。。结果是【%s】,异常是【%s】", result, exception));
        }).exceptionally(throwable -> {
            //可以感知异常,出现异常的时候同时返回默认值
            return 10;
        });
        Integer integer = supplyAsync.get();
        System.out.println(integer);
        System.out.println("handle的使用------------------------------------------------------------------------");
        /**
         * handle的使用
         */
        CompletableFuture<Integer> supply = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 16 / 2;
            return i;
        }, service).handle((result,thread)->{
            if (result != 0) {
                return result * 15;
            }
            if (thread != null) {
                return 123;
            }
            return 456;
        });
        System.out.println(supply.get());
        System.out.println("线程串行化------------------------------------------------------------------------");
        /**
         * 线程串行化
         * thenRunAsync 只要上面任务执行完成,就开始执行thenRun。不能获取上一步执行结果,无返回值
         * thenAcceptAsync 接收上面任务的处理结果,无返回值
         * thenApplyAsync 接收上面的任务处理结果,有返回值
         */
        CompletableFuture<String> async = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            return i;
        }, service).thenApplyAsync(result -> {
            System.out.println(result + "当前线程" + Thread.currentThread().getId());
            return "处理结果";
        }, service);
        System.out.println(async.get());

        System.out.println("多任务组合------------------------------------------------------------------------");

        /**
         * allOf:等待所有任务完成
         * anyOf:只要有一个任务完成
         */
        ArrayList<CompletableFuture> cFList = new ArrayList<>();

        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程01" + Thread.currentThread().getId());
            return "我是线程1";
        }, service);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程02" + Thread.currentThread().getId());
            return "我是线程2";
        }, service);

        CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("线程03" + Thread.currentThread().getId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "我是线程3";
        }, service);

        cFList.add(future01);
        cFList.add(future02);
        cFList.add(future03);

        CompletableFuture.allOf(cFList.toArray(new CompletableFuture[cFList.size()])).join();

        System.out.println("两任务组合,一个完成的情况------------------------------------------------------------------------");
        /**
         * 当两个任务中,任意一个future任务完成的时候,执行任务
         * applyToEither():两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值
         * acceptEither():两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值
         * runAfterEither():两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值
         */

        System.out.println("两任务组合,都要完成的情况------------------------------------------------------------------------");
        /**
         * 两个任务必须都完成,触发该任务
         * thenCombine():组合两个future,获取两个future的返回结果,并返回当前任务的返回值
         * thenAcceptBoth():组合两个future,获取两个future的返回结果,然后处理任务,没有返回值
         * runAfterBoth():组合两个future,不需要获取future的结果,字需要两个future处理完任务后,处理该任务。
         */



    }

    public static class Thread01 extends Thread{
        @Override
        public void run() {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("jieguo:" + i);
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值