English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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的测试示例:
@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("成功 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-ライブラリ/ウィキ/ListenableFutureExplained
Guava - 並行プログラミングの Futures の資料整理を行い、今後も関連する資料を追加し続けます。皆様の本サイトへのサポートに感謝します!
声明:本文の内容はインターネットから取得しており、著作権者は所有しておりません。インターネットユーザーにより自発的に提供された内容であり、本サイトは所有権を持ちません。また、人工的な編集は行われていません。著作権侵害が疑われる内容がある場合は、メールを送信していただければ幸いです:notice#oldtoolbag.com(メール送信時は、#を@に変更してください)で通報してください。関連する証拠を提供していただければ、本サイトは即座に侵害疑いの内容を削除します。