线程池实战

本文只是记录在工作中用到线程池的用法以及处理的方案:

public class TPkTopicAppointmentHandlerApplicationService {
    private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(4, 8, 6000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10), new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "tpk_topic_appointment_msg-" + threadNumber.getAndIncrement());
        }
    });

    @Resource
    private TPkTopicAppointmentMapper tPkTopicAppointmentDao;

    @Resource
    private  TPkTopicService tPkTopicService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${campaigns.tpktopicappointment.push.page:0}")
    private Integer page;

    @Value("${campaigns.tpktopicappointment.push.pageSize:1000}")
    private Integer pageSize;

    @Value("${campaigns.tpktopicappointment.push.isBatch:true}")
    private Boolean isBatch;

    @Value("${campaigns.tpktopicappointment.push.time:10}")
    private Integer times;

    @Autowired
    private ISendMessageService sendMessageService;

    @Value("${no.sign.seven.tpktopicappointment.messageCode:RW2524007023139552}")
    private String noSignSevenMessageCode;

    public void pushUserExpringCoinsMsg() throws ParseException {
        log.info("pushUserExpringCoinsMsg begin");
        String key="pushUserExpringCoinsMsg";
        String result = redisUtil.get(key);

        List<TPkTopicVo> tPkTopics =new ArrayList<>(10);
        if(StringUtils.isNotBlank(result) && CollectionUtils.isEmpty(JSONArray.parseArray(result, TPkTopicVo.class))){
            result = null;
        }
        if(StringUtils.isEmpty(result)){
            Date now = new Date();
            //60分钟
            long time = 60 * 60 * 1000;
            long times = 10 * 60 * 1000;
            //60分钟后的时间
            Date afterDate = new Date(now.getTime() + time);
            TPkTopicVo topic=new TPkTopicVo();
            topic.setTopicStatus(1);
            Date afterDates = new Date(now.getTime() - times);
            topic.setDate(afterDates);
            topic.setDateAfter(afterDate);
            //查看已经上架 并且定时任务1小时内的话题pk
            tPkTopics = tPkTopicService.queryAllByAll(topic);
            redisUtil.set(key, JSONObject.toJSONString(tPkTopics),30 * 60 * 1000);
        }else{
            //缓存数据
            tPkTopics = JSONArray.parseArray(result, TPkTopicVo.class);
            log.info("pushUserExpringCoinsMsg redis{}",tPkTopics);
        }

        Date date = new Date();


        for (TPkTopicVo  x:
                tPkTopics) {
            //延时多久
            long time = 10 * 60 * 1000;
            Date afterDate = new Date(x.getBeginTime().getTime() + time);
            //如果当前时间大于 话题pk开始时间 证明话题已经开始 就可以进行推送消息
            log.info("pushUserExpringCoinsMsg bejin{}",x.getBeginTime());
            if (date.compareTo(x.getBeginTime()) > 0 && afterDate.compareTo(date) > 0) {
                log.info("pushUserExpringCoinsMsg bejin{}",x.getBeginTime());
                List<TPkTopicAppointment> tPkTopicAppointments = new ArrayList<>(10);
                TPkTopicAppointment tPkTopicAppointment = new TPkTopicAppointment();
                tPkTopicAppointment.setTopicId(x.getId());
                tPkTopicAppointments.addAll(tPkTopicAppointmentDao.queryAllByAll(tPkTopicAppointment));
                //参与预约的人员
                List<String> userIdList = tPkTopicAppointments.stream().map(y -> y.getUserId()).collect(Collectors.toList());
                log.info("pushUserExpringCoinsMsg userIdList{}",userIdList);
                int listSize = userIdList.size();

                if (userIdList.size() < ((page-1) * pageSize)) {
                    log.info("话题PK消息推送完成");
                } else {
                    for (int i = 0; i < userIdList.size(); i += pageSize) {
                        // 如果线程满了睡5秒 防止提醒的消息丢失了
                        while (((ThreadPoolExecutor) EXECUTOR_SERVICE).getActiveCount() == 8) {
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                log.error("pushUserExpringCoinsMsg.thread{}" + e.getMessage(), e);
                                return;
                            }
                        }
                        // toIndex作用为:最后没有b条数据时,则l中剩余几条l2中就装几条
                        if (i + pageSize > listSize) {
                            pageSize = listSize - i;
                        }
                        //要发送消息的userid
                        List<String> pushUserIds = userIdList.subList(i, i + pageSize);
                        EXECUTOR_SERVICE.submit(() -> {
                            try {
                                if(!CollectionUtils.isEmpty(pushUserIds)){
                                    log.info("话题PK推送消息开始,page[{}],用户ids[{}]", page, pushUserIds);
                                    if (isBatch){
                                        sendMessageService.sendMessage(pushUserIds,noSignSevenMessageCode,null);
                                    }
                                    log.info("话题PK推送消息结束,page[{}],用户ids[{}]", page, pushUserIds);
                                }
                            } catch (Exception e) {
                                log.error("话题PK用户[{}]消息推送失败:", pushUserIds, e);
                            }
                        });
                        //发送完删除redis
                        redisUtil.del(key);
                    }
                }
            }
        };

    }
    public void send(){
        List<String> pushUserIds = new ArrayList<>();
        pushUserIds.add("1467698925477040128");
        sendMessageService.sendMessage(pushUserIds,noSignSevenMessageCode,null);
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String createTime ="2022-12-13 10:05:00";
        Date date = sdf.parse(createTime);
        if(date.compareTo(new Date()) > 0){
            System.out.println(1111);
        }


//
//        System.out.println("当前时间:" + sdf.format(now));
//
//        //30分钟
//        long time = 30*60*1000;
//        //30分钟后的时间
//        Date afterDate = new Date(now .getTime() + time);
//        //30分钟前的时间
//        Date beforeDate = new Date(now .getTime() - time);
//        System.out.println(afterDate);
//        System.out.println(beforeDate);
//        if (afterDate.compareTo(now) > 0) {
//            System.out.println("Date1 时间在 Date2 之后");
//        }
//        int a = 0;
//        List l = new ArrayList();
//        l.add("图图");
//        l.add("涂涂");
//        l.add("花花");
//        l.add("帅帅");
//        l.add("爽爽");
//        l.add("凤凤");
//        l.add("爱爱");
//        l.add("莲莲");
//        l.add("红红");
//        l.add("特特");
//        l.add("哈哈");
//        l.add("哼哼");
//        l.add("呵呵");
//        int listSize = l.size();
//        int toIndex = 6;
//        List<List<String>> l3 = new ArrayList<>();
//
//        if (l.size() < ((a-1) * toIndex)) {
//            System.out.println("没有更多数据");
//        } else {
//            for (int i = 0; i < l.size(); i += toIndex) {
//                // toIndex作用为:最后没有b条数据时,则l中剩余几条l2中就装几条
//                if (i + toIndex > listSize) {
//                    toIndex = listSize - i;
//                }
//                List<String> l2 = l.subList(i, i + toIndex);
//                System.out.println(l2);
//                l3.add(l2);
//            }
//            System.out.println("输出第a条记录:");
//            System.out.println(l3.get(a));
//        }





    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值