多線程執(zhí)行帶有返回結(jié)果

CompletableFuture 通用異步編程

1. 多線程異步執(zhí)行,帶有返回值方法,避免使用get獲取結(jié)果集會(huì)阻塞線程.

2. 具體執(zhí)行業(yè)務(wù)邏輯方法

       () -> { System.out.println(Thread.currentThread().getName() + "------come in");
        int result = ThreadLocalRandom.current().nextInt(10);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("---計(jì)算完成等待一秒鐘輸出結(jié)果");
        return result;

3. 正常執(zhí)行結(jié)束

        if (e == null) {
            System.out.println("輸出完成" + v);
        }

4. 異常執(zhí)行結(jié)束

      e.printStackTrace();
        System.out.println("執(zhí)行異常");
        return null;

5. CompletableFuture好處

     public static void main(String[] args) {
   ExecutorService executorService = Executors.newFixedThreadPool(3);
    try {
        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "------come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {   TimeUnit.SECONDS.sleep(1);  } catch (InterruptedException e) { e.printStackTrace();  }
            System.out.println("---計(jì)算完成等待一秒鐘輸出結(jié)果");
            return result;
        },executorService).whenComplete((v, e) -> {//當(dāng)執(zhí)行結(jié)束
            if (e == null) {System.out.println("輸出完成" + v);} }).exceptionally(e -> {e.printStackTrace();System.out.println("執(zhí)行異常");
            return null;
        });
        System.out.println("主線程執(zhí)行其他任務(wù)");
        //主線程不要立刻結(jié)束,否則CompletableFuture默認(rèn)使用的線程池會(huì)立刻關(guān)閉,暫停三秒鐘結(jié)束
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        executorService.shutdown();
    }
}

簡化執(zhí)行任務(wù)閉并返回?cái)?shù)據(jù)

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    //調(diào)用異步有返回值方法
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
        System.out.println(Thread.currentThread().getName());
        return "hello word";
    },executorService);
    System.out.println(completableFuture.get());
    executorService.shutdown();
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容