CompletableFuture

CompletableFuture.runAsync    传入一个Runable任务,异步执行没有返回值。可以用thenRun()方法链式调用让任务按顺序执行。

CompletableFuture.supplyAsync     传入一个Runable任务,异步执行有返回值。通过get方法获取。

CompletableFuture.allof(); 传入多个CompletableFuture对象,阻塞当前主线程,当所有CompletableFuture的任务完成后继续。

CompletableFuture.anyof() 传入多个CompletableFuture对象,阻塞当前主线程,当其中一个CompletableFuture的任务完成后继续。

 1 public static void main(String[] args) throws InterruptedException {
 2         long begin = System.currentTimeMillis();
 3         CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
 4             try {
 5                 System.out.println("Fuete doing");
 6                 Thread.sleep(1000);
 7                 System.out.println("task one doing" );
 8             } catch (InterruptedException e) {
 9                 throw new RuntimeException(e);
10             }
11         }).thenRun(() -> {
12             try {
13                 Thread.sleep(1000);
14             } catch (InterruptedException e) {
15                 throw new RuntimeException(e);
16             }
17             System.out.println("task two doing");
18         });
19         System.out.println("main doing");
20         for (int i = 0; i < 5; i++){
21             System.out.println(i);
22             Thread.sleep(200);
23         }
24         future.join();
25         System.out.println((System.currentTimeMillis() - begin)+"ms");
26     }
链式调用

 

 

 

posted @ 2026-01-20 20:24  意凌云丶  阅读(0)  评论(0)    收藏  举报