使用CompletableFuture实现异步

创建日期:2024-06-21
更新日期:2024-12-10
import java.util.concurrent.CompletableFuture;

public class Application {
    public static void main(String[] args) {
        CompletableFuture<String> future1 = futureCall();
        CompletableFuture<String> future2 = futureCall();

        try {
            CompletableFuture.allOf(future1, future2).whenComplete((s, ext) -> {
                try {
                    System.out.println(future1.get());
                    System.out.println(future2.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("done");
    }

    public static CompletableFuture<String> futureCall() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("hello");
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "world";
        });
    }
}