怎么获得一个CompletabeFuture
用核心的四个静态方法来创建一个异步任务,不推荐使用 new CompletableFuture() 来创建。如下图所示
无返回结果调用
//无返回值 public class CompeltableFutureBuildDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { // CompletableFuture CompletableFuture = new CompletableFuture();//不推荐 CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> { System.out.println(Thread.currentThread().getName()); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println(voidCompletableFuture.get()); } } 结果: ForkJoinPool.commonPool-worker-1(用默认线程池) null public class CompeltableFutureBuildDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { // CompletableFuture CompletableFuture = new CompletableFuture();//不推荐 ExecutorService threadPool = Executors.newFixedThreadPool(3); CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> { System.out.println(Thread.currentThread().getName()); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } },threadPool); System.out.println(voidCompletableFuture.get()); } } 结果: pool-1-thread-1(自己的线程池的名称) null
有返回值的调用
public class CompeltableFutureBuildDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { // CompletableFuture CompletableFuture = new CompletableFuture();//不推荐 ExecutorService threadPool = Executors.newFixedThreadPool(3); CompletableFuture<String> voidCompletableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName()); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "hello supplyAsync"; },threadPool); System.out.println(voidCompletableFuture.get()); } } 运行结果: pool-1-thread-1 (自己new的线程池) hello supplyAsync (返回结果)