国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Java組合式異步編程CompletableFuture

這篇具有很好參考價(jià)值的文章主要介紹了Java組合式異步編程CompletableFuture。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。


前言

CompletableFuture是Java 8中引入的一個(gè)功能強(qiáng)大的Future實(shí)現(xiàn)類,它的字面翻譯是“可完成的Future”。 CompletableFuture對(duì)并發(fā)編程進(jìn)行了增強(qiáng),可以方便地將多個(gè)有一定依賴關(guān)系的異步任務(wù)以流水線的方式組合在一起,大大簡化多異步任務(wù)的開發(fā)。

CompletableFuture實(shí)現(xiàn)了兩個(gè)接口,一個(gè)是Future,另一個(gè)是CompletionStage,F(xiàn)uture表示異步任務(wù)的結(jié)果,而CompletionStage字面意思是完成階段,多個(gè)CompletionStage可以以流水線的方式組合起來,對(duì)于其中一個(gè)CompletionStage,它有一個(gè)計(jì)算任務(wù),但可能需要等待其他一個(gè)或多個(gè)階段完成才能開始,它完成后,可能會(huì)觸發(fā)其他階段開始運(yùn)行。

CompletableFuture的設(shè)計(jì)主要是為了解決Future的阻塞問題,并提供了豐富的API來支持函數(shù)式編程和流式編程,可以更方便地組合多個(gè)異步任務(wù),并處理它們的依賴關(guān)系和異常。這使得它在處理并發(fā)編程和異步編程時(shí)非常有用。

在使用CompletableFuture時(shí),可以創(chuàng)建它的實(shí)例,并通過其提供的各種方法(如thenApply、thenCompose、thenAccept等)來定義任務(wù)之間的依賴關(guān)系和執(zhí)行順序。同時(shí),CompletableFuture還提供了異常處理機(jī)制,可以更方便地處理任務(wù)執(zhí)行過程中可能出現(xiàn)的異常。


一、CompletableFuture基本用法

  • 靜態(tài)方法supplyAsync
CompletableFuture.supplyAsync(Supplier<U> supplier, Executor executor)

方法接受兩個(gè)參數(shù)supplier和executor,使用executor執(zhí)行supplier表示的任務(wù),返回一個(gè)CompletableFuture,調(diào)用后,任務(wù)被異步執(zhí)行,這個(gè)方法立即返回。
supplyAsync還有一個(gè)不帶executor參數(shù)的方法:

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

沒有executor,任務(wù)被誰執(zhí)行呢?與系統(tǒng)環(huán)境和配置有關(guān),一般來說,如果可用的CPU核數(shù)大于2,會(huì)使用Java 7引入的Fork/Join任務(wù)執(zhí)行服務(wù),即ForkJoinPool.commonPool(),該任務(wù)執(zhí)行服務(wù)背后的工作線程數(shù)一般為CPU核數(shù)減1,即Runtime.getRuntime().availableProcessors()-1,否則,會(huì)使用ThreadPerTaskExecutor,它會(huì)為每個(gè)任務(wù)創(chuàng)建一個(gè)線程。

對(duì)于CPU密集型的運(yùn)算任務(wù),使用Fork/Join任務(wù)執(zhí)行服務(wù)是合適的,但對(duì)于一般的調(diào)用外部服務(wù)的異步任務(wù),F(xiàn)ork/Join可能是不合適的,因?yàn)樗牟⑿卸缺容^低,可能會(huì)讓本可以并發(fā)的多任務(wù)串行運(yùn)行,這時(shí),應(yīng)該提供Executor參數(shù)。


import java.util.Random;
import java.util.concurrent.*;
import java.util.function.Supplier;


public class CompletableFutureDemo {
    private static ExecutorService executor = Executors.newFixedThreadPool(10);
    private static Random rnd = new Random();
    static int delayRandom(int min, int max) {
        int milli = max > min ? rnd.nextInt(max - min) : 0;
        try {
            Thread.sleep(min + milli);
        } catch (InterruptedException e) {
        }
        return milli;
    }
    static Callable<Integer> externalTask = () -> {
        int time = delayRandom(20, 2000);
        return time;
    };
    public static void master() {
        Future<Integer> asyncRet = callExternalService();
        try {
            Integer ret = asyncRet.get();
            System.out.println(ret);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    public static CompletableFuture<Integer> callExternalService(){
        Supplier<Integer> supplierTask = () -> {
            int time = delayRandom(20, 2000);
            return time;
        };
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(supplierTask);
        return future;
    }
    public static void main(String[] args) throws Exception{
//        master();
        CompletableFuture<Integer> integerFuture = callExternalService();
        boolean done = integerFuture.isDone();
        Integer now = integerFuture.getNow(0);
        System.out.println(now);
        Integer result = integerFuture.get();
        System.out.println(result);
        now = integerFuture.getNow(0);
        System.out.println(now);
//        executor.shutdown();
    }
}

二、使用CompletableFuture來調(diào)度執(zhí)行由JSON串定義的DAG

在這個(gè)例子中,我們創(chuàng)建了四個(gè)任務(wù):A、B、C 和 D。任務(wù)B依賴于任務(wù)A的結(jié)果,而任務(wù)D依賴于任務(wù)B和任務(wù)C的結(jié)果。我們使用thenApplyAsync來創(chuàng)建依賴鏈,并使用CompletableFuture.allOf來等待多個(gè)任務(wù)的完成。最后,我們使用get方法來獲取結(jié)果。文章來源地址http://www.zghlxwxcb.cn/news/detail-845619.html


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import java.util.concurrent.CompletableFuture;  
import java.util.concurrent.ExecutionException;  
import java.util.function.Supplier;  
  
public class DagScheduler {  
  
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String dagJson = "{\"nodes\": [{\"id\": \"A\", \"task\": \"printA\"}, {\"id\": \"B\", \"task\": \"printB\", \"dependencies\": [\"A\"]}, {\"id\": \"C\", \"task\": \"printC\", \"dependencies\": [\"A\"]}, {\"id\": \"D\", \"task\": \"printD\", \"dependencies\": [\"B\", \"C\"]}]}";
        Map<String, CompletableFuture<Void>> futures = new HashMap<>();  
  
        // 解析JSON串  
        JSONObject dagObject = JSONObject.parseObject(dagJson);
        JSONArray nodesArray = dagObject.getJSONArray("nodes");
  
        // 創(chuàng)建一個(gè)映射,用于存儲(chǔ)每個(gè)節(jié)點(diǎn)的CompletableFuture  
        Map<String, Node> nodeMap = new HashMap<>();  
        for (int i = 0; i < nodesArray.size(); i++) {
            JSONObject nodeObj = nodesArray.getJSONObject(i);  
            String id = nodeObj.getString("id");  
            List<String> dependencies = new ArrayList<>();  
            if (nodeObj.containsKey("dependencies")) {
                dependencies = nodeObj.getJSONArray("dependencies").toJavaList(String.class);
            }  
            Node node = new Node(id, () -> executeTask(id), dependencies);  
            nodeMap.put(id, node);  
        }  
  
        // 構(gòu)建依賴關(guān)系并啟動(dòng)任務(wù)  
        for (Node node : nodeMap.values()) {  
            node.start(futures, nodeMap);  
        }  
  
        // 等待所有任務(wù)完成  
        CompletableFuture.allOf(futures.values().toArray(new CompletableFuture[0])).get();  
        System.out.println("All tasks completed.");  
    }  
  
    private static Void executeTask(String taskId) {
        // 執(zhí)行任務(wù)的具體邏輯  
        System.out.println("Executing task: " + taskId);  
        // 模擬任務(wù)執(zhí)行時(shí)間  
        try {  
            Thread.sleep((long) (Math.random() * 1000));  
        } catch (InterruptedException e) {  
            Thread.currentThread().interrupt();  
            throw new IllegalStateException(e);  
        }
        return null;
    }  
  
    static class Node {  
        private final String id;  
        private final Supplier<Void> task;
        private final List<String> dependencies;  
        private CompletableFuture<Void> future;
  
        public Node(String id, Supplier<Void> task, List<String> dependencies) {
            this.id = id;  
            this.task = task;  
            this.dependencies = dependencies;  
        }  
  
        public void start(Map<String, CompletableFuture<Void>> futures, Map<String, Node> nodeMap) {
            List<CompletableFuture<Void>> depFutures = new ArrayList<>();
            for (String depId : dependencies) {  
                CompletableFuture<Void> depFuture = futures.get(depId);
                if (depFuture == null) {  
                    throw new IllegalStateException("Unknown dependency: " + depId);  
                }  
                depFutures.add(depFuture);  
            }  
  
            if (depFutures.isEmpty()) {  
                // 沒有依賴,直接執(zhí)行任務(wù)  
                future = CompletableFuture.supplyAsync( task);
            } else {  
                // 等待所有依賴完成后執(zhí)行任務(wù)  
                future = CompletableFuture.allOf(depFutures.toArray(new CompletableFuture[0])).thenRunAsync(()->executeTask(id));
            }  
  
            futures.put(id, future);  
        }  
    }  
}

到了這里,關(guān)于Java組合式異步編程CompletableFuture的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Vue3組合式API

    Vue3組合式API

    目錄 composition API vs options API 體驗(yàn) composition API setup 函數(shù) reactive 函數(shù) ref 函數(shù) script setup 語法 計(jì)算屬性 computed 函數(shù) 監(jiān)聽器 watch 函數(shù) 生命周期 模板中 ref 的使用 組件通訊 - 父傳子 組件通訊 - 子傳父 依賴注入 - provide 和 inject 保持響應(yīng)式 - toRefs 函數(shù) vue2 采用的就是 options API (

    2024年02月07日
    瀏覽(22)
  • js繼承的幾種方式(原型鏈繼承、構(gòu)造函數(shù)繼承、組合式繼承、寄生組合式繼承、ES6的Class類繼承)

    js繼承的幾種方式(原型鏈繼承、構(gòu)造函數(shù)繼承、組合式繼承、寄生組合式繼承、ES6的Class類繼承)

    實(shí)現(xiàn)原理: 子類的原型指向父類實(shí)例 。子類在自身實(shí)例上找不到屬性和方法時(shí)去它父類實(shí)例(父類實(shí)例和實(shí)例的原型對(duì)象)上查找,從而實(shí)現(xiàn)對(duì)父類屬性和方法的繼承 缺點(diǎn): 子類創(chuàng)建時(shí)不能傳參(即沒有實(shí)現(xiàn)super()的功能); 父類實(shí)例的修改會(huì)影響子類所有實(shí)例 實(shí)現(xiàn)原理:

    2024年02月07日
    瀏覽(31)
  • vue3組合式API介紹

    根據(jù)官方的說法,vue3.0的變化包括性能上的改進(jìn)、更小的 bundle 體積、對(duì) TypeScript 更好的支持、用于處理大規(guī)模用例的全新 API,全新的api指的就是本文主要要說的組合式api。 在 vue3 版本之前,我們復(fù)用組件(或者提取和重用多個(gè)組件之間的邏輯),通常有以下幾種方式: M

    2023年04月22日
    瀏覽(25)
  • 組合式升降壓PFC的分析方法

    組合式升降壓PFC的分析方法

    ??組合式升降壓PFC采用兩組儲(chǔ)能元件,基本單元為Cuk,Sepic和Zeta。參考論文《New Efficient Bridgeless Cuk Rectifiers for PFC Applications》中的三種拓?fù)溥M(jìn)行分析。 ??Cuk型PFC的TypeI如下圖所示,正半周Dp一直導(dǎo)通,Vc1=Vac+Vo。其中Vac=Vacm sinwt,Vo=mVacm。此根據(jù)回路Vac,L1,C1,C2,L2可知,

    2023年04月17日
    瀏覽(25)
  • Vue3 組合式函數(shù),實(shí)現(xiàn)minxins

    Vue3 組合式函數(shù),實(shí)現(xiàn)minxins

    截至目前,組合式函數(shù)應(yīng)該是在VUE 3應(yīng)用程序中組織業(yè)務(wù)邏輯最佳的方法。它讓我們可以把一些小塊的通用邏輯進(jìn)行抽離、復(fù)用,使我們的代碼更易于編寫、閱讀和維護(hù)。 根據(jù)官方文檔說明,在 Vue 應(yīng)用的概念中, “組合式函數(shù)”是一個(gè)利用 Vue 組合式 API 來封裝和復(fù)用有狀態(tài)

    2024年02月08日
    瀏覽(23)
  • 快速入門vue3組合式API

    快速入門vue3組合式API

    (創(chuàng)作不易,感謝有你,你的支持,就是我前行的最大動(dòng)力,如果看完對(duì)你有幫助,請(qǐng)留下您的足跡) 目錄 使用create-vue創(chuàng)建項(xiàng)目 熟悉項(xiàng)目目錄和關(guān)鍵文件? 組合式API? setup選項(xiàng) setup選項(xiàng)的寫法和執(zhí)行時(shí)機(jī) script setup?語法糖 reactive和ref函數(shù) reactive() ref() computed watch 偵聽單個(gè)數(shù)據(jù)

    2024年02月12日
    瀏覽(23)
  • vue3 組合式 api 單文件組件寫法

    Vue3 中的 Composition API 是一種新的編寫組件邏輯的方式,它提供了更好的代碼組織、類型推導(dǎo)、測試支持和復(fù)用性。相比于 Vue2 的 Options API,Composition API 更加靈活和可擴(kuò)展。 在 Composition API 中,我們使用 setup 函數(shù)來定義組件的邏輯部分。setup 函數(shù)是一個(gè)特殊的函數(shù),在創(chuàng)建組

    2024年02月12日
    瀏覽(20)
  • 基于Vue組合式API的實(shí)用工具集

    基于Vue組合式API的實(shí)用工具集

    今天,給大家分享一個(gè)很實(shí)用的工具庫 VueUse,它是基于 Vue Composition Api,也就是組合式API。支持在Vue2和Vue3項(xiàng)目中進(jìn)行使用,據(jù)說是目前世界上Star最高的同類型庫之一。 圖片 官方地址: https://vueuse.org/ 中文地址: https://www.vueusejs.com/ github: https://github.com/vueuse/vueuse 圖片 鏈接

    2024年01月23日
    瀏覽(20)
  • vue3組合式api單文件組件寫法

    一,模板部分? 二,js邏輯部分?

    2024年02月13日
    瀏覽(23)
  • vue3組合式寫法在方法中出發(fā)點(diǎn)擊事件

    vue3組合式寫法在方法中出發(fā)點(diǎn)擊事件

    問: 用vue3組合式寫法,如何在一個(gè)方法中調(diào)用a標(biāo)簽的點(diǎn)擊事件 回答: 在Vue 3的組合式API中,可以通過ref來獲取DOM元素的引用,然后使用$el屬性訪問DOM元素并觸發(fā)其點(diǎn)擊事件。下面是示例代碼: 在上述代碼中,首先通過ref創(chuàng)建了一個(gè)名為linkRef的引用變量,并將其初始化為

    2024年02月15日
    瀏覽(20)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包