Guava為Java并行編程Future提供了很多有用擴展,其主要接口為ListenableFuture,并借助于Futures靜態擴展。
繼承至Future的ListenableFuture,允許我們添加回調函數在線程運算完成時返回值或者方法執行完成立即返回。
對ListenableFuture添加回調函數:
Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)
其中 FutureCallback是一個包含onSuccess(V),onFailure(Throwable)的接口。
使用如:
Futures.addCallback(ListenableFuture, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.printf("onSuccess with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure %s%n", thrown.getMessage()); }});同時Guava中Futures對于Future擴展還有:
下邊是一個對于Future的測試demo:
@Testpublic void should_test_furture() throws Exception { ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture future1 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 1."); return 1; } }); ListenableFuture future2 = service.submit(new Callable<Integer>() { public Integer call() throws InterruptedException { Thread.sleep(1000); System.out.println("call future 2."); // throw new RuntimeException("----call future 2."); return 2; } }); final ListenableFuture allFutures = Futures.allAsList(future1, future2); final ListenableFuture transform = Futures.transform(allFutures, new AsyncFunction<List<Integer>, Boolean>() { @Override public ListenableFuture apply(List<Integer> results) throws Exception { return Futures.immediateFuture(String.format("success future:%d", results.size())); } }); Futures.addCallback(transform, new FutureCallback<Object>() { public void onSuccess(Object result) { System.out.println(result.getClass()); System.out.printf("success with: %s%n", result); } public void onFailure(Throwable thrown) { System.out.printf("onFailure%s%n", thrown.getMessage()); } }); System.out.println(transform.get());}官方資料主頁:https://awk.so/@code.google.com!/p/guava-libraries/wiki/ListenableFutureExplained
以上就是對Guava - 并行編程Futures 的資料整理,后續繼續補充相關資料謝謝大家對本站的支持!
新聞熱點
疑難解答