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 "调用商品微服务";
}
}
标签:调用,汇总,System,线程,println,new,public,out
From: https://www.cnblogs.com/goodluckxiaotuanzi/p/18361304