AsyncFuntion接口与之前学习吃的使用Function和Functions进行对象转换有很密切的联系,AsyncFuction接口是Function接口的异步表现,AsyncFuction和Function都需要接收一个input参数,不同的是AsyncFunction接口返回的是 ListenableFuture,当我们需要接收AsyncFunction转换后的结果时,我们需要调用 ListenableFuture.get()方法。
AsyncFunction接口常被用于当我们想要异步的执行转换而不造成线程阻塞时,尽管Future.get()方法会在任务没有完成时造成阻塞,但 是AsyncFunction接口并不被建议用来异步的执行转换,它常被用于返回Future实例。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
public class AsyncFunctionTest {
private static ListeningExecutorService listeningExecutorService =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
static AsyncFunction<String, String> asyncFunction = new AsyncFunction<String, String>() {
@Override
public ListenableFuture<String> apply(final String input) throws Exception {
return listeningExecutorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return input + "101";
}
});
}
};
static ListenableFuture<String> lis = listeningExecutorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "张三";
}
});
public static void main(String[] args) throws InterruptedException, ExecutionException {
ListenableFuture<String> lf =
Futures.transform(lis, asyncFunction);
System.out.println(lf.get());
listeningExecutorService.shutdown();
}
}