* @description CompletableFuture 是各种任务的管理类 ,CompletableFuture.allOf 所有执行的任务都有结果才可以返回 * CompletableFuture.anyOf 所有执行的任务有一个有结果就可以返回
public class T_CompletableFuture {@SneakyThrowspublic static void main(String[] args) {long start = System.currentTimeMillis();// 声明异步任务及结果CompletableFuture<Double> futureTM=CompletableFuture.supplyAsync(()->priceOfTM());CompletableFuture<Double> futureJD=CompletableFuture.supplyAsync(()->priceOfJD());CompletableFuture<Double> futurePDD=CompletableFuture.supplyAsync(()->priceOfPDD());// 等待所有任务执行完毕,该方法无返回值,通过CompletableFuture回去结果CompletableFuture.allOf(futureTM, futureJD, futurePDD).join();// 所有执行的任务有一个有结果就可以返回,返回结果是获取的这个结果Object join = CompletableFuture.anyOf(futureTM, futureJD, futurePDD).join();/* CompletableFuture.supplyAsync(()->priceOfTM()).thenApply(String::valueOf).thenApply(str->"price: "+str).thenAccept(System.out::println);*/long end = System.currentTimeMillis();System.out.println("use CompletableFuture! cost = "+(end-start));}static Double priceOfTM(){DateUtil.sleep(1000);return 2.0;}static Double priceOfJD(){DateUtil.sleep(2000);return 3.0;}static Double priceOfPDD(){DateUtil.sleep(3000);return 1.8;}
}