Java工具库Guava并发相关工具类的使用示例

场景

Java核心工具库Guava介绍以及Optional和Preconditions使用进行非空和数据校验:

Java核心工具库Guava介绍以及Optional和Preconditions使用进行非空和数据校验_霸道流氓气质的博客-CSDN博客

Java中ExecutorService线程池的使用(Runnable和Callable多线程实现):

Java中ExecutorService线程池的使用(Runnable和Callable多线程实现)_霸道流氓气质的博客-CSDN博客

在上面分别使用Java的ExecutorService以及Guava的入门介绍,看一下Guava中对于并发

的相关工具类的使用。

Guava 定义了ListenableFuture接口并继承了 JDK concurrent 包下的 Future 接口。

ListeningExecutorService接口继承于juc中的ExecutorService接口,对ExecutorService做了一些扩展,

看其名字中带有Listening,说明这个接口自带监听的功能,可以监听异步执行任务的结果。

通过MoreExecutors.listeningDecorator创建一个ListeningExecutorService对象,需传递一个ExecutorService参数,

传递的ExecutorService负责异步执行任务。

传统 JDK 中的 Future 通过异步的方式计算返回结果:在多线程运算中可能或者可能在没有结束返回结果,

Future 是运行中的多线程的一个引用句柄,确保在服务执行返回一个 Result。

ListenableFuture 可以允许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用,

或者在运算(多线程执行)完成后立即执行。这样简单的改进,使得可以明显的支持更多的操作,

这样的功能在 JDK concurrent 中的 Future 是不支持的。

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

执行单个任务并添加回调-通过submit.addListener

    @Test
    public void test1() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        try {

            ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
            ListenableFuture<Integer> submit = listeningExecutorService.submit(() -> {
                System.out.println(System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(System.currentTimeMillis());
                return 10;
            });

            submit.addListener(()-> System.out.println("任务执行成功,进入回调"),MoreExecutors.directExecutor());
            System.out.println("任务执行结果:"+submit.get());
        }finally {
            executorService.shutdown();
        }
    }

执行单个任务并添加回调-通过Futures.addCallback

    @Test
    public void test1() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        try {

            ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
            ListenableFuture<Integer> submit = listeningExecutorService.submit(() -> {
                System.out.println(System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(System.currentTimeMillis());
                return 10;
            });

            //写法一
            //        submit.addListener(()-> System.out.println("任务执行成功,进入回调"),MoreExecutors.directExecutor());
            //        System.out.println("任务执行结果:"+submit.get());

            //写法二
            //通过调用Futures的静态方法addCallback在异步执行的任务中添加回调,回调的对象是一个FutureCallback,此对象有2个方法,
            // 任务执行成功调用onSuccess,执行失败调用onFailure。
            Futures.addCallback(submit, new FutureCallback<Integer>() {
                @Override
                public void onSuccess(@Nullable Integer integer) {
                    System.out.println("执行成功");
                }
                @Override
                public void onFailure(Throwable throwable) {
                    System.out.println("执行失败:" + throwable.getMessage());
                }
            }, MoreExecutors.directExecutor());

            System.out.println("任务执行结果:" + submit.get());
        }finally {
            executorService.shutdown();
        }
    }

执行多个任务并获取所有的结果Futures.allAsList

    @Test
    public void test2() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        try {
            List<ListenableFuture<Integer>> futureList = new ArrayList<>();
            ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
            for (int i = 0; i < 5; i++) {
                int finalI = i;
                Future<?> submit = listeningExecutorService.submit(() -> {
                    TimeUnit.SECONDS.sleep(finalI);
                    return finalI;
                });
                futureList.add((ListenableFuture<Integer>) submit);
            }
            List<Integer> integers = Futures.allAsList(futureList).get();
            integers.stream().forEach(System.out::println);
        }finally {
            executorService.shutdown();
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值