等待所有任务执行完, 串行执行和异步执行的高级写法:
package com.zhangxueliang.demo.springbootdemo.JUC.c_026_01_ThreadPool;import java.util.Random;import java.pletableFuture;import java.util.concurrent.TimeUnit;/*** @ProjectName springbootdemo_src* @ClassName T06_01_CompletableFuture* @Desicription TODO* @Author Zhang Xueliang* @Date /12/5 16:13* @Version 1.0**/public class T06_01_CompletableFuture {public static void main(String[] args) {long start,end;start=System.currentTimeMillis();/*priceOfJD();priceOfTB();priceOfTM();*/CompletableFuture<Double> priceOfTM = CompletableFuture.supplyAsync(() -> priceOfTM());CompletableFuture<Double> priceOfJD = CompletableFuture.supplyAsync(() -> priceOfJD());CompletableFuture<Double> priceOfTB = CompletableFuture.supplyAsync(() -> priceOfTB());CompletableFuture.allOf(priceOfJD,priceOfTB,priceOfTM).join();end=System.currentTimeMillis();System.out.println(end-start);}private static double priceOfTM() {delay();return 1.00;}private static double priceOfTB() {delay();return 2.00;}private static double priceOfJD() {delay();return 3.00;}private static void delay() {int time = new Random().nextInt(500);try {TimeUnit.MILLISECONDS.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}System.out.printf("After %s sleep!\n", time);}}
Completable好玩的API:
package com.zhangxueliang.demo.springbootdemo.JUC.c_026_01_ThreadPool;import java.util.Random;import java.pletableFuture;import java.util.concurrent.TimeUnit;/*** @ProjectName springbootdemo_src* @ClassName T06_01_CompletableFuture* @Desicription TODO* @Author Zhang Xueliang* @Date /12/5 16:13* @Version 1.0**/public class T06_01_CompletableFuture {public static void main(String[] args) {CompletableFuture.supplyAsync(()->priceOfJD()).thenApply(String::valueOf).thenApply(str->"price "+str).thenAccept(System.out::println);while (true){}}private static double priceOfTM() {delay();return 1.00;}private static double priceOfTB() {delay();return 2.00;}private static double priceOfJD() {delay();return 3.00;}private static void delay() {int time = new Random().nextInt(500);try {TimeUnit.MILLISECONDS.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}System.out.printf("After %s sleep!\n", time);}}