future用法 - java中异步执行多个任务并集中处理所有结果

需求背景

同事问了个问题,java中有什么办法让我异步查询多个表的数据,最后将所有结果进行处理输出
想到future是解决这类问题常用的,于是写了个demo给他参考

简化需求

定义3个任务分别获取1个字符串,每个任务耗时300ms
最后进行合并输出

直接代码

package future;

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

/**
 * @author: wod.Y
 * @date: 2022/4/25 17:36
 */
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        CompletableFuture[] futures = new CompletableFuture[3];
        //定义三个异步任务
        futures[0] = CompletableFuture.supplyAsync(FutureDemo::getString1);
        futures[1] = CompletableFuture.supplyAsync(FutureDemo::getString2);
        futures[2] = CompletableFuture.supplyAsync(FutureDemo::getString3);
        //让任务开始运行
        CompletableFuture.allOf(futures).join();
        //收集结果
        String result = "";
        for (CompletableFuture future : futures) result += future.join() + " ";
        long spend = System.currentTimeMillis() - start;
        System.out.println("spend:[" + spend + "ms],result:" + result);
    }

    static String getString1() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    }

    static String getString2() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "future";
    }

    static String getString3() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "shit";
    }
}

结果说明

控制台输出:spend:[406ms],result:hello future shit
三个任务每个任务300ms,最后执行任务并合并结果共耗时 406ms,可以说是达到了效果

posted @ 2022-04-25 18:42  杨海星  阅读(1814)  评论(0编辑  收藏  举报