线程池使用场景 调用多个微服务汇总数据

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.concurrent.*;

public class T {

    @SneakyThrows
    public static void main(String[] args) {
        shopping_threadPool();
    }

    /* 汇总数据使用线程池+Future 耗时≈所有微服务中用时最长的时间

    购物开始:2024-08-15 04:41:13 385
    调用商品微服务
    调用订单微服务
    调用物流微服务
    购物结束:2024-08-15 04:41:18 397
    * */
    @SneakyThrows
    public static void shopping_threadPool() {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 5, 0,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>(1));

        System.out.println("购物开始:" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS")
                        .format(System.currentTimeMillis()));

        Callable<String> product = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return product();
            }
        };

        Callable<String> order = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return order();
            }
        };

        Callable<String> logistics = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return logistics();
            }
        };

        Future<String> productService = threadPool.submit(product);
        Future<String> orderService = threadPool.submit(order);
        Future<String> logisticsService = threadPool.submit(logistics);
        System.out.println(productService.get());
        System.out.println(orderService.get());
        System.out.println(logisticsService.get());

        System.out.println("购物结束:" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS")
                        .format(System.currentTimeMillis()));
    }

    /*
    购物开始:2024-08-15 04:40:25 240
    调用商品微服务
    调用订单微服务
    调用物流微服务
    购物结束:2024-08-15 04:40:33 263
    * */
    public static void shopping_ordinary() {
        System.out.println("购物开始:" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS")
                        .format(System.currentTimeMillis()));
        System.out.println(product());
        System.out.println(order());
        System.out.println(logistics());
        System.out.println("购物结束:" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS")
                        .format(System.currentTimeMillis()));
    }

    @SneakyThrows
    public static String logistics() {
        Thread.sleep(5000);
        return "调用物流微服务";
    }

    @SneakyThrows
    public static String order() {
        Thread.sleep(2000);
        return "调用订单微服务";
    }

    @SneakyThrows
    public static String product() {
        Thread.sleep(1000);
        return "调用商品微服务";
    }

}
posted @ 2024-08-15 16:44  干饭达人GoodLucy  阅读(4)  评论(0编辑  收藏  举报