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 的资料整理,后续继续补充相关资料谢谢大家对本站的支持!
新闻热点
疑难解答