代碼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); } }