CompletableFuture异步编程

Future和Callable接口

  • Future接口定义了操作异步任务执行一些方法,如获取异步任务的执行结果、取消任务的执行、判断任务是否被取消、判断任务执行是否完毕等。
  • Callable接口中定义了需要有返回的任务需要实现的方法
  • join和get对比,get会抛出异常,join不需要
  • 示例代码如下
/**
 * FutureTask & Callable
 * 异步任务执行
 */
public class FutureTaskTest {

    public static void main(String[] args) {
        FutureTask<String> task = new FutureTask<>(new MyThread());
        //task.run(); 执行任务线程
        Thread t1 = new Thread(task, "t1");
        t1.start();
        try {
            String res = task.get(); //获取返回结果,容易导致程序执行阻塞
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyThread implements Callable<String>{

    @Override
    public String call() throws Exception {
        System.out.println("come in call()...");
        return "hello callable";
    }
}

CompletableFuture类

这里是引用
在这里插入图片描述
在这里插入图片描述

核心的四个静态方法

//runAsync 无返回值
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor)

//supplyAsync 有返回值  
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor)
//没有指定Executor的方法,
//直接使用默认的ForkJoinPool.commonPool() 作为它的线程池执行异步代码。
runAsync无返回值
/**
 * CompletableFuture
 * 静态方法 runAsync 无返回值
 */
public class CompletableFutureTest01 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建线程池

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("run task...");
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },threadPool); //默认有线程池,也可自定义指定

        try {
            System.out.println(completableFuture.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPool.shutdown(); //关闭线程池
    }
}
supplyAsync有返回值
/**
 * CompletableFuture
 * 静态方法 supplyAsync 有返回值
 */
public class CompletableFutureTest02 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建线程池

        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("run task...");
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello supplyAsync";
        },threadPool); //默认有线程池,也可自定义指定

        try {
            System.out.println(completableFuture.get()); //获取返回结果
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPool.shutdown(); //关闭线程池
    }
}

CompletableFuture常用方法

supplyAsync有返回值,回调函数 & 异常处理
/**
 * CompletableFuture
 * 静态方法 supplyAsync 有返回值
 * 回调函数 & 异常处理
 */
public class CompletableFutureTest03 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建线程池
        try {

            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println("run task...");
                System.out.println(Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int res = ThreadLocalRandom.current().nextInt(10);//产生随机数
                //res/=0; //模拟异常
                return res;
            },threadPool).whenComplete((v,e)->{ //任务执行完毕,回调函数
                if (e==null){
                    System.out.println("任务执行完毕,没有出错!res="+v);
                }
            }).exceptionally(e->{ //任务执行出现异常,异常处理
                System.err.println("出现的异常:=>>"+e.getCause());
                return null;
            });

            System.out.println(completableFuture.get()); //获取返回结果

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown(); //关闭线程池
        }
    }
}
supplyAsync有返回值,返回结果处理
  • thenApply(无异常处理) & handle(有异常处理)
/**
 * CompletableFuture
 * 返回结果处理 thenApply(无异常处理) & handle(有异常处理)
 *
 *             thenApply(f->{
 *                 return f+2;
 *             })
 *
 *            handle((v,e)->{
 *                 if (e==null){
 *                     return v+2;
 *                 }
 *                 System.err.println(e.getCause());
 *                 return null;
 *             })
 */
public class CompletableFutureTest04 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建线程池
        try {

            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println("run task...");
                System.out.println(Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int res = 1;
                //res/=0; //模拟异常
                return res;
            },threadPool).handle((v,e)->{
                if (e==null){
                    return v+2;
                }
                System.err.println(e.getCause());
                return null;
            }).whenComplete((v, e)->{ //任务执行完毕,回调函数
                if (e==null){
                    System.out.println("任务执行完毕,没有出错!res="+v);
                }
            }).exceptionally(e->{ //任务执行出现异常,异常处理
                System.err.println("出现的异常:=>>"+e.getCause());
                return null;
            });

            System.out.println(completableFuture.get()); //获取返回结果

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown(); //关闭线程池
        }
    }
}
supplyAsync有返回值,返回结果消费 (消费完 无返回值)
  • thenRun & thenAccept
/**
 * CompletableFuture
 * 返回结果消费 (消费完 无返回值)
 * thenRun & thenAccept
 */
public class CompletableFutureTest05 {

    public static void main(String[] args) {
        //重新启动一个线程,无需上一个任务结果和传入参数
        System.out.println(CompletableFuture.supplyAsync(()->"A").thenRun(()->{}).join());

        //消费上一个任务结果
        System.out.println(CompletableFuture.supplyAsync(()->"A").thenAccept(r->{
            System.out.println(r);
        }).join());
    }
}
supplyAsync有返回值,比较两个任务计算速度 (谁快)
  • applyToEither
/**
 * CompletableFuture
 * 比较两个任务计算速度 (谁快)
 * applyToEither
 */
public class CompletableFutureTest06 {

    public static void main(String[] args) {
        CompletableFuture<String> res1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "1号";
        });

        CompletableFuture<String> res2 =CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "2号";
        });

        CompletableFuture<String> ans = res1.applyToEither(res2, f -> {
            return f + "is win";
        });

        System.out.println(ans.join());
    }
}
supplyAsync有返回值,合并两个任务计算结果
  • thenCombine
/**
 * CompletableFuture
 * 合并两个任务计算结果
 * thenCombine
 */
public class CompletableFutureTest07 {

    public static void main(String[] args) {
        CompletableFuture<Integer> res1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });

        CompletableFuture<Integer> res2 =CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 20;
        });

        CompletableFuture<Integer> ans = res1.thenCombine(res2,(x,y)->{
            return x+y;
        });

        System.out.println(ans.join());
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值