package J20250801.homework;

import java.util.concurrent.*;

/**
 * @author WanJl
 * @version 1.0
 * @title Demo06
 * @description
 * @create 2025/8/1
 */
public class Demo06 {
    private static int successCount=0;
    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(
                20, //核心线程数
                50,//最大线程数
                60l,//线程空余最大存活时间
                TimeUnit.SECONDS,//时间单位
                new LinkedBlockingQueue<>(500), //工作队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.DiscardOldestPolicy()//拒绝策略，扔掉最久的，加入当前的
        );
        //记录开始时间
        long startTime = System.currentTimeMillis();
        //提交1000个下单请求
        for (int i = 0; i < 1000; i++) {
            //用户id
            final int userId=i+1;
            poolExecutor.submit(()->{
                try {
                    //模拟下单处理耗时50ms
                    System.out.println("用户"+userId+"下单中...");
                    Thread.sleep(50);
                    successCount++;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("用户"+userId+"下单被中断");
                }
            });
        }
        //关闭线程池
        poolExecutor.shutdown();
        //等待所有任务完成
        try {
            if(!poolExecutor.awaitTermination(1,TimeUnit.MINUTES)){
                poolExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            poolExecutor.shutdownNow();
        }


        //记录结束时间
        long endTime = System.currentTimeMillis();
        long time=endTime-startTime;
        System.out.println("------处理结果统计------");
        System.out.println("总耗时："+time+"毫秒");
        System.out.println("成功处理的订单数为："+successCount);
        System.out.println("被拒绝的订单数为："+(1000-successCount));
    }
}
