线程池使用例子

本文介绍如何在数据库更新后利用线程池并发执行发送短信的任务,优化了资源利用并确保了高并发场景下的稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、构造一个线程池

private static ThreadPoolExecutor threadPoolExecutor;

    static {
        //构造一个线程池
        //	corePoolSize:线程池维护线程的最少数量
        //	maximumPoolSize:线程池维护线程的最大数量
        //	keepAliveTime: 线程池维护线程所允许的空闲时间
        //	unit: 线程池维护线程所允许的空闲时间的单位
        //	workQueue: 线程池所使用的缓冲队列
        //	handler: 线程池对拒绝任务的处理策略
        threadPoolExecutor = new ThreadPoolExecutor(2, 10, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }


2、更新数据库之后线程池中发送短信

    private Long saveOrUpdateTodo(WfProcessTodo todo, Boolean isSendMsg, String sendMsgContent) {
        if (todo.save()) {
            // 线程池中发送短信和短消息
            threadPoolExecutor.execute(
                    new Thread() {
                        public void run() {
                            try{
                                //发送消息
//                                messageService.sendInnerMessage(sendMsgContent, "", todo.processOperatorId, -1, messageSourceService.getMessage("system"));
                                //发送短信
                                if (isSendMsg) {
                                    messageService.sendSMS(todo.processOperatorId, sendMsgContent);
                                }
                            }catch(Exception e){
                                log.error("发送消息或短信失败", e)
                            }
                        }
                    }
            );
            return todo.id;
        } else {
            throw new LogicException(DomainErrorUtil.formatDomainErrors(todo.errors));
        }
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值