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

Java CompletableFuture之異步執(zhí)行、鏈?zhǔn)秸{(diào)用、組合多個(gè)Future、異常處理和超時(shí)控制等詳解

 更新時(shí)間:2025年05月29日 10:02:14   作者:學(xué)亮編程手記  
這篇文章主要介紹了Java CompletableFuture之異步執(zhí)行、鏈?zhǔn)秸{(diào)用、組合多個(gè)Future、異常處理和超時(shí)控制等用法,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Java ComputableFuture 代碼示例

CompletableFuture 是 Java 8 引入的一個(gè)強(qiáng)大的異步編程工具,它實(shí)現(xiàn)了 Future 接口并提供了更豐富的功能。

以下是一些常見的 CompletableFuture 使用示例:

1. 基本用法

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureBasicExample {
    public static void main(String[] args) {
        // 創(chuàng)建一個(gè)CompletableFuture并異步執(zhí)行任務(wù)
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000); // 模擬耗時(shí)操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, CompletableFuture!";
        });
        
        // 注冊完成時(shí)的回調(diào)
        future.thenAccept(result -> System.out.println("Result: " + result));
        
        // 阻塞等待結(jié)果
        try {
            String result = future.get();
            System.out.println("Main thread got: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

2. 鏈?zhǔn)秸{(diào)用

import java.util.concurrent.CompletableFuture;

public class CompletableFutureChainExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            // 第一個(gè)異步任務(wù)
            System.out.println("Task 1 running in thread: " + Thread.currentThread().getName());
            return "Hello";
        }).thenApplyAsync(result -> {
            // 第二個(gè)異步任務(wù),接收上一個(gè)任務(wù)的結(jié)果
            System.out.println("Task 2 running in thread: " + Thread.currentThread().getName());
            return result + " World";
        }).thenAcceptAsync(result -> {
            // 第三個(gè)異步任務(wù),消費(fèi)最終結(jié)果
            System.out.println("Task 3 running in thread: " + Thread.currentThread().getName());
            System.out.println("Final result: " + result);
        }).join(); // 等待所有任務(wù)完成
    }
}

3. 組合多個(gè) Future

import java.util.concurrent.CompletableFuture;

public class CompletableFutureCombineExample {
    public static void main(String[] args) {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
        
        // 合并兩個(gè)Future的結(jié)果
        CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2);
        
        combinedFuture.thenAccept(System.out::println).join();
    }
}

4. 異常處理

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("Something went wrong!");
            }
            return "Success";
        }).exceptionally(ex -> {
            System.out.println("Exception occurred: " + ex.getMessage());
            return "Recovered from exception";
        }).thenAccept(System.out::println).join();
    }
}

5. 并行執(zhí)行多個(gè)任務(wù)

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CompletableFutureAllOfExample {
    public static void main(String[] args) {
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            sleep(1);
            return "Task 1";
        });
        
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            sleep(2);
            return "Task 2";
        });
        
        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
            sleep(3);
            return "Task 3";
        });
        
        // 等待所有任務(wù)完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(task1, task2, task3);
        
        // 獲取所有任務(wù)的結(jié)果
        CompletableFuture<String> combinedFuture = allFutures.thenApply(v -> {
            String result1 = task1.join();
            String result2 = task2.join();
            String result3 = task3.join();
            return result1 + ", " + result2 + ", " + result3;
        });
        
        System.out.println("Combined result: " + combinedFuture.join());
    }
    
    private static void sleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

6. 超時(shí)處理(Java 9+)

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CompletableFutureTimeoutExample {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000); // 模擬耗時(shí)操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Result";
        });
        
        // 設(shè)置超時(shí)時(shí)間為1秒
        CompletableFuture<String> timeoutFuture = future.orTimeout(1, TimeUnit.SECONDS);
        
        timeoutFuture.whenComplete((result, ex) -> {
            if (ex != null) {
                System.out.println("Exception: " + ex.getClass().getName());
                if (ex.getCause() instanceof TimeoutException) {
                    System.out.println("Task timed out");
                }
            } else {
                System.out.println("Result: " + result);
            }
        }).join();
    }
}

這些示例展示了 CompletableFuture 的主要功能,包括異步執(zhí)行、鏈?zhǔn)秸{(diào)用、組合多個(gè) Future、異常處理和超時(shí)控制等。CompletableFuture 是 Java 并發(fā)編程中非常強(qiáng)大的工具,可以大大簡化異步編程的復(fù)雜性。

總結(jié)

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

相關(guān)文章

  • 查看import的類是出自哪個(gè)jar包的方法

    查看import的類是出自哪個(gè)jar包的方法

    下面小編就為大家?guī)硪黄榭磇mport的類是出自哪個(gè)jar包的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-03-03
  • IDEA中關(guān)于enter鍵換行的問題

    IDEA中關(guān)于enter鍵換行的問題

    這篇文章主要介紹了IDEA中關(guān)于enter鍵換行的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Spring核心IoC和AOP的理解

    Spring核心IoC和AOP的理解

    本文主要介紹了Spring核心IoC和AOP的相關(guān)知識。具有很好的參考價(jià)值,下面跟著小編一起來看下吧
    2017-03-03
  • 基于Java字符串 "==" 與 "equals" 的深入理解

    基于Java字符串 "==" 與 "equals" 的深入理解

    本篇文章是對Java中的字符串"=="與"equals"進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • Java中的比較器詳細(xì)解析

    Java中的比較器詳細(xì)解析

    這篇文章主要介紹了Java中的比較器詳細(xì)解析,基本數(shù)據(jù)類型的數(shù)據(jù)(除boolean類型外)需要比較大小的話,直接使用比較運(yùn)算符即可,但是引用數(shù)據(jù)類型是不能直接使用比較運(yùn)算符來比較大小的,需要的朋友可以參考下
    2023-11-11
  • Java基于NIO實(shí)現(xiàn)群聊功能

    Java基于NIO實(shí)現(xiàn)群聊功能

    這篇文章主要為大家詳細(xì)介紹了Java基于NIO實(shí)現(xiàn)群聊功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Mybatis解決找不到get方法

    Mybatis解決找不到get方法

    這篇文章主要介紹了Mybatis解決找不到get方法問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 一文解決pom.xml報(bào)錯(cuò)Dependency "xxx" not found的問題

    一文解決pom.xml報(bào)錯(cuò)Dependency "xxx" not f

    我們在使用maven進(jìn)行jar包管理時(shí)有時(shí)會遇到pom.xml中報(bào)錯(cuò)Dependency “XXX” not found,所以在本文中將給大家介紹一下pom.xml報(bào)錯(cuò)Dependency "xxx" not found的解決方案,需要的朋友可以參考下
    2024-01-01
  • 詳解MybatisPlus集成nacos導(dǎo)致druid連接不上數(shù)據(jù)庫

    詳解MybatisPlus集成nacos導(dǎo)致druid連接不上數(shù)據(jù)庫

    這篇文章主要介紹了詳解MybatisPlus集成nacos導(dǎo)致druid連接不上數(shù)據(jù)庫,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • java 正則表達(dá)式獲取兩個(gè)字符中間的字符串方法

    java 正則表達(dá)式獲取兩個(gè)字符中間的字符串方法

    今天小編就為大家分享一篇java 正則表達(dá)式獲取兩個(gè)字符中間的字符串方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07

最新評論

清镇市| 高清| 德格县| 司法| 夏邑县| 眉山市| 莆田市| 永顺县| 道真| 涿鹿县| 集贤县| 平果县| 贡嘎县| 枣强县| 永靖县| 镇康县| 普陀区| 集贤县| 犍为县| 寿光市| 佳木斯市| 宁阳县| 泰兴市| 墨玉县| 焦作市| 兰西县| 龙州县| 阿尔山市| 普兰店市| 简阳市| 旬邑县| 铜山县| 水富县| 太仓市| 崇仁县| 四会市| 凌云县| 宜丰县| 溧水县| 屯留县| 屏边|