Java 9 - CompletableFuture API 改进

package com.lfsun.java9study.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CompletableFutureImprovementsExample {
    
    

    public static void main(String[] args) {
    
    
        // 示例1:newIncompleteFuture 方法
        CompletableFuture<String> future = new CompletableFuture<>();
        future.thenAccept(result -> System.out.println("Result: " + result));

        // 模拟在稍后的时间点完成 CompletableFuture
        new Thread(() -> {
    
    
            try {
    
    
                TimeUnit.SECONDS.sleep(2);
                future.complete("Hello, World thenAccept!");
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }).start();

        // 示例2:completeAsync 方法的增强
        Executor executor = Executors.newFixedThreadPool(4);

        CompletableFuture<String> future2 = new CompletableFuture<>();
        future2.completeAsync(() -> "Hello, World completeAsync!", executor)
                .thenAccept(result -> System.out.println("Result: " + result));

        // 示例3:orTimeout 方法
        CompletableFuture<String> future3 = new CompletableFuture<>();
        future3.orTimeout(5, TimeUnit.SECONDS)
                .exceptionally(throwable -> {
    
    
                    System.out.println("Timeout occurred!");
                    return null;
                });

        try {
    
    
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }

        // 等待所有任务完成
        try {
    
    
            future.get();
            future2.get();
        } catch (InterruptedException | ExecutionException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            System.out.println("all is complete!");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/131818305