Guava - 並行編程Futures詳解。本站提示廣大學習愛好者:(Guava - 並行編程Futures詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Guava - 並行編程Futures詳解正文
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:
@Test public 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.谷歌.com!/p/guava-libraries/wiki/ListenableFutureExplained
以上就是對Guava - 並行編程Futures 的材料整頓,後續持續彌補相干材料感謝年夜家對本站的支撐!