美文网首页
ListenableFuture demo

ListenableFuture demo

作者: grasslike | 来源:发表于2021-12-29 15:13 被阅读0次

使用ListenableFuture

使用一种可监听的future 测试demo

public class TestListenableFuture {


    public static void main(String[] args) {
        ExecutorService delegate = Executors.newSingleThreadExecutor();
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(delegate);

        Callable callable  = new Callable<String>() {
            @Override
            public String call() throws Exception {
                int i = 0;
                while (true){
                    Thread.currentThread().sleep(3000);
                    i++;
                    System.out.println("test call ,count =" + i);
                    if (i == 5){
                        System.out.println(1/0);
                        return "liyan";
                    }
                }

            }
        };
        ListenableFuture submit = listeningExecutorService.submit(callable);
        /**
        添加监听线程, 在任务成功或失败时候做出反应
        */
        Futures.addCallback(submit, new FutureCallback<String>() {
            @Override
            public void onSuccess(@Nullable String result) {
                System.out.println(" ok ,success");
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("not ok ,exeception "  + t.getMessage() );
            }
        },listeningExecutorService);


        int i = 0;
        while (true){
            try {
                Thread.currentThread().sleep(3000);
                i++;
                System.out.println("main thread  ,count =" + i);

            }catch (Exception e){

            }
        }

    }
}

相关文章

  • ListenableFuture demo

    使用ListenableFuture 使用一种可监听的future 测试demo

  • [Guava]ListenableFuture的使用

    ListenableFuture定义 介绍ListenableFuture之前先介绍下Future,Future是...

  • ListenableFuture

    Future要获取异步任务执行的结果,需要通过轮询或者阻塞等待的方式,这样的方式,总显得不太“完美”,比较好的做法...

  • Guava——ListenableFuture

    缘由 To simplify matters, Guava extends the Future interfac...

  • hsf笔记-ListenableFuture

    1.Future扩展 ListenableFuture和SettableFuture类似于Netty的Promis...

  • Guava学习之ListenableFuture

    本文是对 Guava 中 ListenableFuture 的学习介绍。欢迎加入学习项目: LearningGua...

  • ListenableFuture源码解析

    jdk原生的future已经提供了异步操作,但是不能直接回调。guava对future进行了增强,核心接口就是Li...

  • Guava-ListenableFuture

    处理并发是一个很困难的问题,但是我们可以通过使用功能强大的抽象来简化这个工作。为了简化这个问题,Guava 提供了...

  • guava异步增强——ListenableFuture

    guava异步增强——ListenableFuture jdk原生的future已经提供了异步操作,但是不能直接回...

  • 线程池(1)

    ListenableFuture顾名思义就是可以监听的Future,它是对java原生Future的扩展增强。我们...

网友评论

      本文标题:ListenableFuture demo

      本文链接:https://www.haomeiwen.com/subject/psivqrtx.html