Java核心複習——CompletableFuture

介紹

JDK1.8引入CompletableFuture類。html

使用方法

public class CompletableFutureTest {

    private static ExecutorService threadPool = new ThreadPoolExecutor(40, 100,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(20));

    public String B() {
        System.out.println("執行方法B");
        sleep(5);
        return "Function B";
    }

    public String C() {
        System.out.println("執行方法C");
        sleep(20);
        return "Function C";
    }


    public void sleep(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void testCompableFuture() {
        CompletableFuture<String> future;
        try {
            //Returns a new CompletableFuture 
            // that is asynchronously completed by a task running in the given executor 
            // with the value obtained by calling the given Supplier.
            future = CompletableFuture.supplyAsync(() -> B(), threadPool);
            //若去掉線程池,有何區別future = CompletableFuture.supplyAsync(() -> B());

            sleep(9);
            System.out.println(future.toString());
            System.out.println(future.isDone());
        } catch (RejectedExecutionException e) {
            System.out.println("調用搜索列表服務線程滿負荷, param:{}");
        }
    }

    public static void main(String[] args) {
        CompletableFutureTest test = new CompletableFutureTest();
        test.testCompableFuture();
    }

}

API

supplyAsync方法

JDK方法描述java

/**
     * Returns a new CompletableFuture that is asynchronously completed
     * by a task running in the given executor with the value obtained
     * by calling the given Supplier.
     *
     * @param supplier a function returning the value to be used
     * to complete the returned CompletableFuture
     * @param executor the executor to use for asynchronous execution
     * @param <U> the function's return type
     * @return the new CompletableFuture
     */
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }

應用場景

請求A的執行方法X,需知足下列需求:api

①請求B、C、D中任一一個請求有返回結果,則X方法返回響應結果。oracle

②請求B、C、D中都執行完,則X方法返回響應結果。async

源碼閱讀

依賴關係

在這裏插入圖片描述

參考文檔

JDK API文檔 20 個使用 Java CompletableFuture的例子url

相關文章
相關標籤/搜索