CompletableFuture

CompletableFuture是幹啥的,此處不再贅述,網上資料很多。我就拿一個簡單的應用來直觀的說明它的作用。

應用場景:把一個串行操作優化爲並行操作。減少程序執行的時間開銷。

此處有三個操作,fun1、fun2、fun3,代碼如下

    private static String fun1() {
        try {
            sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "fun1";
    }

    private static String fun2() {
        try {
            sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "fun2";
    }

    private static String fun3() {
        try {
            sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "fun3";
    }

按照我們正常的執行邏輯,也就是串行執行,很明顯,肯定是大於8s的。代碼如下

    private static void test() {
        long startTime = System.currentTimeMillis();
        String s1 = fun1();
        String s2 = fun2();
        String s3 = fun3();
        System.out.println(Thread.currentThread().getName() + "線程耗時:" + (System.currentTimeMillis() - startTime));
        System.out.println(s1 + s2 + s3);
    }

 運行結果

main線程耗時:8002
fun1fun2fun3

現在,我們通過CompletableFuture進行優化,改爲並行執行,代碼如下

    private static void testCompletableFuture() {
        long startTime = System.currentTimeMillis();
        CompletableFuture cf1 = CompletableFuture.supplyAsync(MyCompleteFuture::fun1);
        CompletableFuture cf2 = CompletableFuture.supplyAsync(MyCompleteFuture::fun2);
        CompletableFuture cf3 = CompletableFuture.supplyAsync(MyCompleteFuture::fun3);
        String result = (String) cf1.thenCombine(cf2, (s1, s2) -> s1 + "" + s2).thenCombine(cf3, (s1, s2) -> s1 + "" + s2).join();

        System.out.println(Thread.currentThread().getName()+"線程耗時:"+(System.currentTimeMillis() - startTime));
        System.out.println(result);
    }

運行結果

main線程耗時:3079
fun1fun2fun3

通過執行時間,由8s縮短爲3s。這個提升是很明顯的。

總結一下,有如下幾點:

1.CompletableFuture是java8提供的支持併發編程的一個異步非阻塞的功能。通過它,可以優雅的獲取異步執行的結果,也可以合併多個異步執行的結果。而不像Future那樣,必須要阻塞的獲取結果。

2.CompletableFuture封裝很多併發編程的技術,降低了併發編程的門檻。

3.結合函數式編程,使併發編程的代碼更加優雅,簡潔。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章