Java future 异步返回超时处理

资料

Java多线程 CompletableFuture详解: https://www.cnblogs.com/myhomepages/p/16516737.html

Java future 异步返回超时处理

package org.example;

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

public class Main {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行有返回值的异步任务");
            try {
                for (int i = 0; i < 5; i++) {
                    System.out.println(i);
                    TimeUnit.SECONDS.sleep(1);
                }
//                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "Hello World";
        });
        try {
            System.out.println("等待10s返回:" + future.get(6, TimeUnit.SECONDS));
        } catch (Exception ex) {
            System.out.println("等待10s返回异常");
        }
        if (future.isDone()) {
            System.out.println("返回成功:" + future.isDone());
        } else {
            System.out.println("返回异常:" + future.isDone());
        }

//        System.out.println("立即返回:" + future.get());
    }
}
posted @ 2022-08-25 17:45  西门长海  阅读(369)  评论(0编辑  收藏  举报