溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java多線程開發(fā)工具之CompletableFuture怎么應用

發(fā)布時間:2023-03-20 13:55:18 來源:億速云 閱讀:100 作者:iii 欄目:開發(fā)技術

這篇“Java多線程開發(fā)工具之CompletableFuture怎么應用”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Java多線程開發(fā)工具之CompletableFuture怎么應用”文章吧。

Single Dog拿一個Appointment來舉個列子,如下:

/**
     * 女神化完妝之后,還需要一小會選衣服,不過分吧。
     * 也就是說我們現(xiàn)在有2個異步任務,第一個是化妝,第二個是選衣服。
     * 選衣服要在化妝完成之后進行,這兩個任務是串行
     */
    public static void main(String[] args) {
        // 線程池我前面的文章聊過,怎么配置可以去了解一下
       ThreadPoolExecutor threadPool= new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        //任務1
        CompletableFuture<String> makeUpFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "-女神,開始化妝了");
            try {
                // 化妝的時間
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "化妝完畢了。";
        }, threadPool);
       //任務2,makeUp是調(diào)用方,意思是makeUpFuture執(zhí)行完后再執(zhí)行
        CompletableFuture<String> dressFuture = makeUpFuture.thenApply((result) -> {
            System.out.println(Thread.currentThread().getName() + "-女神" + result + "我開始選衣服啦,好了叫你!");
            try {
                // 換衣服的時間
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return result + "衣服也選好了,走出去玩吧!";
        });
        dressFuture.thenAccept((result) -> {
            System.out.println(Thread.currentThread().getName() + "-" + result);
        });
    }

上面的2個任務也可以理解為我們開發(fā)中要實現(xiàn)的不同功能,看明白前面的列子了吧?用它來寫多線程運用的多絲滑。那我們就先講一下它的核心的靜態(tài)的方法,推薦用它的靜態(tài)方法不要直接new對象。

1:無返回值的靜態(tài)方法:

public static CompletableFuture<Void> runAsync(Runnable runnable)。

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

上面一個2個方法,如果沒有指定Executor就使用默認的ForkJoinPool.commonPool()線程池,如果指定線程池就使用指定的。

2:有返回值的方法

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

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

如果開始的代碼你還看不懂那介紹了上面的幾個方法就先小試牛刀一下:

ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            int i = 10 / 2;
            System.out.println("運行的結(jié)果是:" + i);
        }, threadPool);

        CompletableFuture future = CompletableFuture.supplyAsync(() -> {
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "Hello World";
                }, threadPool);
        System.out.println(future.get());

好了講過它的使用方法了那我們就聊一下它的幾個使用的場景,開發(fā)中這寫場景應該會使用到。

1:執(zhí)行任務 A,執(zhí)行任務B,待任務B執(zhí)行完成后,用B的返回值區(qū)執(zhí)行任務C。

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() ->
        {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("執(zhí)行任務A");
            return "任務A";
        }, executor);
        CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> {
            System.out.println("執(zhí)行任務B");
            return "任務B";
        }, executor);
        CompletableFuture<String> futurec = futureB.thenApply((b) -> {
            System.out.println("執(zhí)行任務C");
            System.out.println("參數(shù):" + b);
            return "a";
        });
        System.out.println(futurec.get());

運行結(jié)果,注意我上面沒說B一定要在A執(zhí)行以后執(zhí)行。

Java多線程開發(fā)工具之CompletableFuture怎么應用

場景2:多個任務串聯(lián)執(zhí)行,下一個任務的執(zhí)行依賴上一個任務的結(jié)果,每個任務都有輸入和輸出。

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture futureA = CompletableFuture.supplyAsync(() -> "Hello", executor);
        CompletableFuture futureB = futureA.thenApply((a) -> a + " World");
        CompletableFuture futureC = futureB.thenApply((b) -> b);
        System.out.println(futureC.join());

輸出結(jié)果,開發(fā)中的經(jīng)典場景輸出:

Java多線程開發(fā)工具之CompletableFuture怎么應用

場景3:thenCombineAsync 聯(lián)合 futureA和futureB的返回結(jié)果,然后在返回相關的數(shù)據(jù)

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> 10, executor);
        CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> 20, executor);
        CompletableFuture futureC = futureA.thenCombineAsync(futureB, (r1, r2) -> {
            System.out.println("r1的值為:" + r1 + ":r2的值為:" + r2);
            return r1 + r2;
        });
        System.out.println(futureC.get());

結(jié)果輸出:

Java多線程開發(fā)工具之CompletableFuture怎么應用

 好了聊完幾個場景那就寫一個在開發(fā)中的經(jīng)典運用。

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        System.out.println("start...");
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("查詢商品信息1");
            return "future1";
        }, executor);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("查詢商品信息2");
            return "future2";
        }, executor);

        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("查詢商品信息3");
            return "future3";
        }, executor);

        final CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3);
        voidCompletableFuture.get();
        System.out.println("end...future1的結(jié)果:" + future1.get() + ",future2的結(jié)果:" + future2.get() + ",future3的結(jié)果:" + future3.get());

輸出結(jié)果

Java多線程開發(fā)工具之CompletableFuture怎么應用

以上就是關于“Java多線程開發(fā)工具之CompletableFuture怎么應用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關的知識內(nèi)容,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI