初探guava 线程回调

代码java

public class ExecutorFactor {
    /*固定线程池数量,MoreExecutors只是为原有的线程池作代理而已,且包装成ListeningExecutorService 这种类型
,下面在submit才能返回ListenableFuture 类型的future*/
    private static ListeningExecutorService EXECUTOR_SERVICE = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    public static void exec(final FutureService objService, final Object... args) {
        // 异步处理
        ListenableFuture<Object> future = EXECUTOR_SERVICE.submit(
                new Callable<Object>() {
                    public Object call() throws Exception {
                        Object o = objService.handler(args);
                        return o;
                    }
                });


        Futures.addCallback(future,new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object o) {
                // TODO 成功处理
                objService.onSuccess(o, args);
            }

            @Override
            public void onFailure(Throwable throwable) {
                // TODO 失败处理
                objService.onFailure(throwable, args);
            }
        },EXECUTOR_SERVICE);
    }
}

这里咱们不妨看下Futures 是如何添加listener 的,点进去异步

public static <V> void addCallback(
      final ListenableFuture<V> future,
      final FutureCallback<? super V> callback,
    //。。。
    这里咱们看下CallbackListener这个类
    future.addListener(new CallbackListener<V>(future, callback), executor);
  }


private static final class CallbackListener<V> implements Runnable {
   //发现是个Runnable 类型的类,那么主要看它的run方法
    @Override
    public void run() {
      final V value;
      try {
        value = getDone(future);
      } catch (ExecutionException e) {
        //若是发生异常就调用异常回调
        callback.onFailure(e.getCause());
        return;
      } catch (RuntimeException e) {
        callback.onFailure(e);
        return;
      } catch (Error e) {
        callback.onFailure(e);
        return;
      }
  //若是正常就调用正常回调
      callback.onSuccess(value);
    }

   
  }
相关文章
相关标签/搜索