CompletableFutrue通过核心的4个静态方法,来创建一个异步任务

  • public static CompletableFuture<Void> runAsync(Runnable runnable)
 1 /**
 2  * public static CompletableFuture<Void> runAsync(Runnable runnable)  不指定线程池, 默认使用 ForkJoinPool.commonPool
 3  */
 4 public class CompletableFutrueDemo {
 5     public static void main(String[] args) throws ExecutionException, InterruptedException {
 6 
 7         CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
 8 
 9             System.out.println(Thread.currentThread().getName());
10 
11             try {
12                 TimeUnit.SECONDS.sleep(3);
13             } catch (InterruptedException e) {
14                 e.printStackTrace();
15             }
16         });
17 
18         System.out.println(completableFuture.get());
19     }
20 }

 

  • public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

 

  • public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

 

  • public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

 

 1 public static void main(String[] args) throws ExecutionException, InterruptedException {
 2 
 3         ExecutorService threadPool = Executors.newFixedThreadPool(3);
 4         try{
 5             CompletableFuture.supplyAsync(() -> {
 6 
 7                 System.out.println(Thread.currentThread().getName());
 8 
 9                 try {
10                     TimeUnit.SECONDS.sleep(3);
11                 } catch (InterruptedException e) {
12                     e.printStackTrace();
13                 }
14 
15 
16                 int i = ThreadLocalRandom.current().nextInt(10);
17 
18                 if (i > 5) {
19                     int r =10 /0;
20                 }
21                 return i;
22             }, threadPool).whenComplete((v, e) -> {
23                 if (e == null) {
24                     System.out.println("计算完成,更新系统updateValue -> " + v);
25                 }
26             }).exceptionally((e) -> {
27                 System.out.println("异常情况");
28                 return null;
29             });
30 
31         } catch (Exception e) {
32             e.printStackTrace();
33         } finally {
34             threadPool.shutdown();
35         }
36     }

 

上述Executor参数说明

没有指定Excutor的方法,直接使用默认的ForkJoinPool.commonPool()作为它的线程池执行异步代码

如果指定线程池,则使用我们自定义的或者特别指定的线程池执行异步代码

 

posted on 2024-06-05 22:27  不会java的菜鸟程序员  阅读(5)  评论(0编辑  收藏  举报