欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Guava包的ListenableFuture解析 博客分类: java  

程序员文章站 2024-03-13 19:10:39
...
package com.downjoy.test.guava.concurrency;

import com.downjoy.test.guava.GuavaBase;
import com.google.common.util.concurrent.*;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * DESCRIPTION.
 *
 * @author Jonathan L.(xingbing.lai@downjoy.com)
 * @version 1.0.0 -- Datetime: 16-8-25 上午10:27
 */
public class ListenableFutureTest extends GuavaBase {

    public static void main(String[] args) throws InterruptedException {
        final ExecutorService pool = Executors.newFixedThreadPool(10);

//        // JDK
//        Future<String> future = pool.submit(new Callable<String>() {
//            public String call() throws Exception {
//                return "D.CN";
//            }
//        });
//
//        try {
//            String name = future.get();
//            print(name);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        // Guava
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(pool);
        ListenableFuture futureTask = executorService.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                return "D.CN";
            }
        });
//        // 运行监控,可以不加
//        futureTask.addListener(new Runnable() {
//            @Override
//            public void run() {
//                print("Game Over !!!");
//            }
//        }, executorService);

        FutureCallbackImpl callback = new FutureCallbackImpl();
        Futures.addCallback(futureTask, callback);
        print(callback.getCallbackResult());

        Thread.sleep(2000);
        pool.shutdown();
    }

    private static class FutureCallbackImpl implements FutureCallback<String> {
        StringBuilder builder = new StringBuilder("结果加点东西>>>");

        @Override
        public void onSuccess(String result) {
            print("success:" + result);
            builder.append(result);
        }

        @Override
        public void onFailure(Throwable t) {
            print("failure:" + t.getMessage());
        }

        public String getCallbackResult(){
            return builder.toString();
        }
    }
}


参考:http://ifeve.com/google-guava-listenablefuture/