123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package J20250801.homework;
- import java.util.ArrayList;
- import java.util.Random;
- import java.util.concurrent.*;
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo07
- * @description
- * @create 2025/8/1
- */
- public class Demo07 {
- private static Random ran=new Random();
- /**
- * 模拟计算用户月度消费
- * @param userId 用户id
- * @return 消费金额(1000~5000)
- */
- public static int getMonthlyConsumption(int userId) throws InterruptedException {
- //模拟计算耗时1~2秒
- int i=1000+ran.nextInt(1001);
- Thread.sleep(i);
- //模拟生成随机消费金额
- int amount=1000+ran.nextInt(4001);
- System.out.println("用户"+userId+"的月度消费计算完成:"+amount+"元");
- return amount;
- }
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- ExecutorService pool = Executors.newCachedThreadPool();
- ArrayList<Future<Integer>> list=new ArrayList<>();
- //提交5个用户的消费计算任务
- for (int i = 0; i < 5; i++) {
- final int userId=i+1;
- Future<Integer> future=pool.submit(()-> getMonthlyConsumption(userId));
- list.add(future);
- }
- //等待所有任务全部完成后收集结果
- int total=0;
- StringBuilder sb=new StringBuilder();
- for (int i = 0; i < list.size(); i++) {
- final int userId=i+1;
- Integer amount = list.get(i).get();
- total+=amount;
- sb.append("用户"+userId+"="+amount);
- if (i<list.size()-1){
- sb.append(",");
- }
- }
- System.out.println("所有用户总共消费:"+total+"元,用户消费明细:"+sb);
- pool.shutdown();
- if (!pool.awaitTermination(3, TimeUnit.SECONDS)){
- pool.shutdownNow();
- }
- }
- }
|