/** * Returns a new CompletableFuture that is asynchronously completed * by a task running in the {@link ForkJoinPool#commonPool()} with * the value obtained by calling the given Supplier. * * @param supplier a function returning the value to be used * to complete the returned CompletableFuture * @param <U> the function's return type * @return the new CompletableFuture */ public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) { return asyncSupplyStage(asyncPool, supplier); }
CompletableFuture下的supplyAsync方法是一个执行异步任务且有返回结果的任务,使用例子如下:
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * 测试类 * @author yangchangkui */ public class TestMy { public static void main(String[] args) throws ExecutionException, InterruptedException { long start = System.currentTimeMillis(); CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return "hello"; }); //判断是否已经完成 System.out.println("耗时:"+(System.currentTimeMillis()-start)+",isDone:"+completableFuture.isDone()); //阻塞获取结果 String result = completableFuture.get(); System.out.println("耗时:"+(System.currentTimeMillis()-start)+",result:"+result); //判断是否已经完成 System.out.println("耗时:"+(System.currentTimeMillis()-start)+",isDone:"+completableFuture.isDone()); } }
执行结果如下,显然,达到了异步执行的效果,比如在一些调用很多外部接口的聚合接口,只要接口不作为入参,那就可以进行异步执行,最后阻塞拿结果,提高接口的QPS,提高系统性能。