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

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 Java工具库Guava并发相关工具类的使用示例,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

场景

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();
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/135861.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!