最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java8?CompletableFuture?runAsync學習總結(jié)submit()?execute()等

 更新時間:2022年10月28日 10:50:02   作者:極光雨雨  
這篇文章主要介紹了Java8?CompletableFuture?runAsync學習總結(jié)submit()?execute()等,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

一般的 Executors 的 execute以及submit

并發(fā)包下 Executors 創(chuàng)建的線程存在 一個 execute(),以及三個 submit()

不同的是使用 execute() 執(zhí)行的任務是沒有返回值的,使用 submit() 則是存在返回值的,這與接下里要說的 CompletableFuture.runAsync 有些類似。

測試代碼如下:

    @Test
    public void justFor(){
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Future<Float> submit = executorService.submit(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        Float aFloat = null;
        try {
            aFloat = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 根據(jù)自己需要決定是否需要調(diào)用關閉線程
//        executorService.shutdown();
        System.out.println("aFloat = " + aFloat);

    }

結(jié)果:

Thread.currentThread() = Thread[pool-2-thread-1,5,main]
aFloat = 1.03

使用 submit 可以通過 get獲取線程中任務的返回結(jié)果,可以通過對象獲取當前狀態(tài) isDone 或者 isCancelled ;

子線程異步執(zhí)行,主線程休眠等待子線程執(zhí)行完成,子線程執(zhí)行完成后喚醒主線程,主線程獲取任務執(zhí)行結(jié)果后退出

此時我加入一個異常代碼,使其必定出錯再來看看結(jié)果

    @Test
    public void justFor(){
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Future<Float> submit = executorService.submit(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            int ii = 1/0;
            return 1.2f;
        });

        Float aFloat = null;
        try {
            aFloat = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
//        executorService.shutdown();
        System.out.println("aFloat = " + aFloat);

    }

執(zhí)行結(jié)果:

此時即使異常依舊終止了子線程以及主線程的執(zhí)行。

CompletableFuture 的 supplyAsync() / runAsync()

  • supplyAsync 表示創(chuàng)建帶返回值的異步任務,相當于ExecutorService submit(Callable< T> task)
  • runAsync 表示創(chuàng)建無返回值的異步任務,相當于ExecutorService submit(Runnable task)方法,這兩個方法效果與 submit 一致

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        try {
            Float aFloat = floatCompletableFuture.get();
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("aFloat = " + aFloat);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

輸出結(jié)果:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
Thread.currentThread() = Thread[main,5,main]
aFloat = 1.03

日志中 ForkJoinPool 為jdk1.7 提供的一個新的分而治之的性能更好的并發(fā)處理線程池,比一般的Executors 更好一點,適用于高密度計算的任務。

但也可以如此寫

即將該任務提交到指定的線程池中執(zhí)行該任務;

輸出的線程池不一致

類似的 runAsync() 也可以這樣,使用自己的異步線程或者提交到指定的線程池中執(zhí)行

可以看得出使用第二個參數(shù)均提供了可以指定 Executor 沒有指定時默認使用 ForkJoinPool.commonPool()

一般的

runAsync 如下:

CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return;
        });

可以看得出 并沒有任何返回值

CompletableFuture 的 thenApply() / thenApplyAsync()

thenApply 表示某個任務執(zhí)行完成后執(zhí)行的動作即回調(diào)方法,會將該任務的執(zhí)行結(jié)果即方法的返回值會作為作為入?yún)鬟f到接下來的回調(diào)方法中

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        CompletableFuture<Float> floatCompletableFuture1 = floatCompletableFuture.thenApply((resultFloat) -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("接受上一個 resultFloat = " + resultFloat);
            return 2.01f;
        });

        CompletableFuture<Float> floatCompletableFuture2 = floatCompletableFuture1.thenApplyAsync((result2) -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("result2 = " + result2);
            return 2.21f;
        });

        try {
            Float aFloat = floatCompletableFuture.get();
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("aFloat = " + aFloat);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

輸出結(jié)果:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
Thread.currentThread() = Thread[main,5,main]
接受上一個 resultFloat = 1.03
Thread.currentThread() = Thread[main,5,main]
Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
aFloat = 1.03
result2 = 2.01

thenApplyAsyncthenApply 區(qū)別:

  • thenApplyAsync 將任務異步處理,可以選擇提交到某一個線程池中執(zhí)行
  • thenApply 則將會在上一個任務的同一個線程中執(zhí)行

上面代碼也可以連著書寫如下:

CompletableFuture 的 thenAccept() / thenRun()

  • thenAccept thenApply 接收上一個任務的返回值作為參數(shù)但是沒有返回值
  • thenAcceptAsync 同上但為異步線程,可以指定提交到某一個線程池中
  • thenRun 方法沒有入?yún)ⅲ矝]有返回值
  • thenRunAsync 同上但為異步線程,可以指定提交到某一個線程池中

示例代碼:

    @Test
    public void justFor(){

        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

         CompletableFuture<Void> floatCompletableFuture1= floatCompletableFuture.thenApply((resultFloat) -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("接受上一個 resultFloat = " + resultFloat);
            return 2.01f;

        }).thenAccept((result)->{
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println("result = " + result);

        }).thenRun(()->{
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            System.out.println(" doNothing");
        });
    }

CompletableFuture exceptionally

指定某個任務執(zhí)行異常時執(zhí)行的回調(diào)方法,會將拋出異常作為參數(shù)傳遞到回調(diào)方法中,如果該任務正常執(zhí)行則 exceptionally方法返回的CompletionStage的result就是該任務正常執(zhí)行的結(jié)果

正常示例:

    @Test
    public void justFor(){

        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
//            float ii = 1/0;
            return 1.03f;
        });

        CompletableFuture<Float> exceptionally = floatCompletableFuture.exceptionally((exception) -> {
            System.out.println("catch exception");
            exception.printStackTrace();
            return 0.0f;
        });

        floatCompletableFuture.thenAccept((result)->{
            System.out.println("is OK");
            System.out.println("result = " + result);
        });

    }

輸出結(jié)果:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
is OK

異常示例:

    @Test
    public void justFor(){

        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());

            int a = 121/0;

            return 1.03f;
        });

        CompletableFuture<Float> exceptionally = floatCompletableFuture.exceptionally((exception) -> {
            System.out.println("catch exception");
            exception.printStackTrace();
            return 0.0f;
        });

        floatCompletableFuture.thenAccept((result)->{
            System.out.println("is OK");
            System.out.println("result = " + result);
        });

    }

結(jié)果:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
catch exception

CompletableFuture whenComplete

當某個任務執(zhí)行完成后執(zhí)行的回調(diào)方法,會將執(zhí)行結(jié)果或者執(zhí)行期間拋出的異常傳遞給回調(diào)方法

  • 正常執(zhí)行則異常為null,回調(diào)方法對應的CompletableFuture的result和該任務一致
  • 異常執(zhí)行,則get方法拋出異常
  • 同樣提供 Async 異步相關方法

正常:

    @Test
    public void justFor(){
        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());

            return 1.03f;
        });

        floatCompletableFuture.whenComplete((result, exception) -> {
            System.out.println("result = " + result);
            System.out.println("exception = " + exception);
        });
    }

輸出:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
result = 1.03
exception = null

異常時示例:

    public static void main(String[] args) {
        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            int ii = 12 / 0;
            return 1.03f;
        });

        floatCompletableFuture.whenComplete((result, exception) -> {
            System.out.println("result = " + result);
            System.out.println("exception = " + exception);
        });
    }

輸出:

Thread.currentThread() = Thread[ForkJoinPool.commonPool-worker-1,5,main]
result = null
exception = java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero

CompletableFuture handle

whenComplete 基本一致

區(qū)別在于handle的回調(diào)方法有返回值,且handle方法返回的CompletableFuture的result是回調(diào)方法的執(zhí)行結(jié)果或者回調(diào)方法執(zhí)行期間拋出的異常,與原始CompletableFuture的result無關

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> floatCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            int ii = 12 / 0;
            return 1.03f;
        });

        floatCompletableFuture.handle((result, exception) -> {
            System.out.println("result = " + result);
            System.out.println("exception = " + exception);

            return "???";
        });
    }

CompletableFuture 組合處理 thenCombine / thenAcceptBoth / runAfterBoth

三個方法都是將兩個 CompletableFuture 組合起來

只有這兩個都正常執(zhí)行完了才會執(zhí)行某個任務區(qū)別在于

  • thenCombine 會將兩個任務的執(zhí)行結(jié)果作為方法入?yún)鬟f到指定方法中,且該方法有返回值;thenAcceptBoth 同樣將兩個任務的執(zhí)行結(jié)果作為方法入?yún)?,但是無返回值;
  • runAfterBoth 沒有入?yún)?,也沒有返回值。注意兩個任務中只要有一個執(zhí)行異常,則將該異常信息作為指定任務的執(zhí)行結(jié)果

同時這些也提供了Async 異步方法

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> a1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        CompletableFuture<Float> a2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 2.03f;
        });

        // 傳遞結(jié)果 有返回值
        CompletableFuture<String> objectCompletableFuture = a1.thenCombine(a2, (a, b) -> {

            return "12";
        });

        // 傳遞結(jié)果  無返回值
        CompletableFuture<Void> voidCompletableFuture = a1.thenAcceptBoth(a2, (a, b) -> {
            
        });

        // 無入?yún)?無返回值
        a1.runAfterBoth(a2, ()->{
            //
        });
    }

CompletableFuture applyToEither / acceptEither / runAfterEither

三個方法都是將兩個CompletableFuture組合起來

但與上面不同的是只要其中一個執(zhí)行完了就會執(zhí)行某個任務,區(qū)別

  • applyToEither 會將已經(jīng)執(zhí)行完成的任務的執(zhí)行結(jié)果作為方法入?yún)?,并有返回值?/li>
  • acceptEither 同樣將已經(jīng)執(zhí)行完成的任務的執(zhí)行結(jié)果作為方法入?yún)ⅲ菦]有返回值;runAfterEither 沒有方法入?yún)?,也沒有返回值。

注意 兩個任務中只要有一個執(zhí)行異常,則將該異常信息作為指定任務的執(zhí)行結(jié)果

同時這些也提供了Async 異步方法

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> a1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        CompletableFuture<Float> a2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 2.03f;
        });

        // 傳遞結(jié)果 有返回值
        CompletableFuture<String> objectCompletableFuture = a1.thenCombine(a2, (a, b) -> {

            return "12";
        });

        // 傳遞結(jié)果  無返回值
        CompletableFuture<Void> voidCompletableFuture = a1.thenAcceptBoth(a2, (a, b) -> {
            
        });

        // 無入?yún)?無返回值
        a1.runAfterBoth(a2, ()->{
            //
        });
    }

CompletableFuture thenCompose

thenCompose

  • 在某個任務執(zhí)行完成后,將該任務的執(zhí)行結(jié)果作為方法入?yún)⑷缓髨?zhí)行指定方法,該方法會返回一個新的CompletableFuture實例
  • 如果該CompletableFuture實例的result不為null,則返回一個基于該result的新的CompletableFuture實例;
  • 如果該CompletableFuture實例為null,則執(zhí)行這個新任務

同樣的提供Async方式

    @Test
    public void justFor(){
        CompletableFuture<Float> a1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        CompletableFuture<Float> a2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 2.03f;
        });

        // 傳遞結(jié)果 有返回值
        CompletableFuture<String> objectCompletableFuture = a1.applyToEither(a2, (b) -> {

            return "12";
        });

        // 傳遞結(jié)果  無返回值
        CompletableFuture<Void> voidCompletableFuture = a1.acceptEither(a2, (b) -> {

        });

        // 無入?yún)?無返回值
        a1.runAfterEither(a2, ()->{
            //
        });
    }

CompletableFuture 的 allOf() anyOf()

  • allOf 返回的CompletableFuture是多個任務都執(zhí)行完成后才會執(zhí)行,只要有一個任務執(zhí)行異常,則返回的 CompletableFuture 執(zhí)行get方法時會拋出異常,如果都正常執(zhí)行,則get返回null
  • anyOf 只要有一個任務執(zhí)行完成,無論是正常執(zhí)行或者執(zhí)行異常,都會執(zhí)行向下執(zhí)行

示例代碼:

    @Test
    public void justFor(){
        CompletableFuture<Float> a1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 1.03f;
        });

        CompletableFuture<Float> a2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Thread.currentThread() = " + Thread.currentThread());
            return 2.03f;
        });

        // 傳遞結(jié)果 有返回值
        CompletableFuture<String> objectCompletableFuture = a1.applyToEither(a2, (b) -> {

            return "12";
        });

        // 傳遞結(jié)果  無返回值
        CompletableFuture<Void> voidCompletableFuture = a1.acceptEither(a2, (b) -> {

        });

        // 無入?yún)?無返回值
        a1.runAfterEither(a2, ()->{
            //
        });
    }

參考文章

點此進入?yún)⒖兼溄?/a>

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Java創(chuàng)建樹形結(jié)構(gòu)算法實例代碼

    Java創(chuàng)建樹形結(jié)構(gòu)算法實例代碼

    本篇文章主要介紹了Java創(chuàng)建樹形結(jié)構(gòu)算法實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-01-01
  • Java?詳細講解線程的狀態(tài)及部分常用方法

    Java?詳細講解線程的狀態(tài)及部分常用方法

    在Java程序中,一個線程對象只能調(diào)用一次start()方法啟動新線程,并在新線程中執(zhí)行run()方法。一旦run()方法執(zhí)行完畢,線程就結(jié)束了,本篇來講解Java線程的狀態(tài)以及部分常用方法
    2022-04-04
  • MyBatis-Plus更新對象時將字段值更新為null的四種常見方法

    MyBatis-Plus更新對象時將字段值更新為null的四種常見方法

    MyBatis-Plus 是一個 MyBatis 的增強工具,在簡化開發(fā)、提高效率方面表現(xiàn)非常出色,而,在使用 MyBatis-Plus 更新對象時,默認情況下是不會將字段值更新為 null 的,如果你需要將某些字段的值更新為 null,有幾種方法可以實現(xiàn),本文將介紹幾種常見的方法
    2024-11-11
  • SpringCloud實戰(zhàn)之Feign聲明式服務調(diào)用

    SpringCloud實戰(zhàn)之Feign聲明式服務調(diào)用

    這篇文章主要介紹了SpringCloud實戰(zhàn)之Feign聲明式服務調(diào)用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Springboot應用gradle?Plugin示例詳解

    Springboot應用gradle?Plugin示例詳解

    這篇文章主要介紹了Springboot應用gradle?Plugin詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • java清除u盤內(nèi)存卡里的垃圾文件示例

    java清除u盤內(nèi)存卡里的垃圾文件示例

    手機內(nèi)存卡空間被用光了,但又不知道哪個文件占用了太大,一個個文件夾去找又太麻煩,開發(fā)了個小程序把手機所有文件(包括路徑下所有層次子文件夾下的文件)進行一個排序,這樣你就可以找出哪個文件占用了內(nèi)存太大了
    2014-02-02
  • Java最長公共子序列示例源碼

    Java最長公共子序列示例源碼

    這篇文章主要介紹了Java最長公共子序列的定義及示例源代碼,具有一定參考價值,需要的朋友可以看下。
    2017-09-09
  • 創(chuàng)建SpringBoot工程并集成Mybatis的方法

    創(chuàng)建SpringBoot工程并集成Mybatis的方法

    這篇文章主要介紹了創(chuàng)建SpringBoot工程并集成Mybatis,需要的朋友可以參考下
    2018-06-06
  • Java 實戰(zhàn)項目之疫情防控管理系統(tǒng)詳解

    Java 實戰(zhàn)項目之疫情防控管理系統(tǒng)詳解

    讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實現(xiàn)一個疫情防控管理系統(tǒng),大家可以在過程中查缺補漏,提升水平
    2021-11-11
  • IDEA x64 exe文件打不開,bat能打開問題

    IDEA x64 exe文件打不開,bat能打開問題

    這篇文章主要介紹了IDEA x64 exe文件打不開,bat能打開問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11

最新評論

修文县| 错那县| 兴安盟| 台州市| 阳信县| 锡林郭勒盟| 忻州市| 绥滨县| 阿合奇县| 玉龙| 平和县| 武平县| 宁城县| 沾益县| 潍坊市| 卓资县| 鹿邑县| 北安市| 马龙县| 赣榆县| 甘洛县| 页游| 武威市| 曲阜市| 珲春市| 盐边县| 民勤县| 洪湖市| 柏乡县| 宣武区| 会理县| 涪陵区| 阳信县| 丰镇市| 射洪县| 岳阳县| 武定县| 桂平市| 女性| 桑植县| 铜山县|