CompletableFuture

package com.example.demo.threadDemo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class CompetableFutuerDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
      /*  CompletableFuture<Void> stringCompletableFuture = CompletableFuture.runAsync(()-> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("11111");
        }).thenRun(
                () -> {System.out.println("22222");}
        );
        Void aVoid = stringCompletableFuture.get();
        System.out.println(aVoid);
         Void v=  stringCompletableFuture.get();
        System.out.println();
        */


       /* CompletableFuture<Void> stringCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    Thread.sleep(3000);
                    System.out.println("23232");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "11111ddd";
            }
        }).thenAccept(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println("2222ddd" +"---" +s);
            }
        });
      Void v=  stringCompletableFuture.get();
        System.out.println();
        */


             CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    Thread.sleep(3000);
                    System.out.println("23232");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "11111ddd";
            }
        }).thenApply(new Function<String, String>() {
                 @Override
                 public String apply(String s) {
                     System.out.println("3333");
                     return s +"---33333333";
                 }
             });
        String s = stringCompletableFuture.get();
        System.out.println(s);
    }
}

 

posted @ 2022-07-09 15:29  不死码农  阅读(81)  评论(0编辑  收藏  举报