线程池使用例子

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));
        }
    }


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用C#开发多线程应用程序时,线程池是一个非常有用的工具,它可以帮助我们更有效地管理和利用线程资源。下面是一个简单的线程池使用例子: ```csharp using System; using System.Threading; class Program { static void Main() { // 创建一个线程池 ThreadPool.QueueUserWorkItem(PrintMessage, "Hello, World!"); Console.WriteLine("Main thread does some other work."); // 等待一段时间,以便观察线程池中的线程执行任务 Thread.Sleep(2000); Console.WriteLine("Main thread finished."); // 需要在程序结束前调用一下,以确保所有任务都被执行完毕 ThreadPool.QueueUserWorkItem(WaitAndPrint, "This is the last message."); Console.ReadLine(); } static void PrintMessage(object state) { string message = (string)state; Console.WriteLine("PrintMessage: " + message); } static void WaitAndPrint(object state) { string message = (string)state; Thread.Sleep(1000); Console.WriteLine("WaitAndPrint: " + message); } } ``` 在上面的例子中,我们首先使用`ThreadPool.QueueUserWorkItem`方法将一个任务放入线程池中执行。然后,主线程继续执行其他工作。在等待一段时间后,我们可以看到线程池中的线程执行了我们放入的任务。 同时,我们还使用了`ThreadPool.QueueUserWorkItem`方法来放置一个最后的任务,以确保它会在程序结束前被执行。这是因为线程池中的任务可能不会立即执行,所以我们需要等待一段时间。 需要注意的是,使用线程池时,我们并不控制具体的线程创建和销毁过程,而是将任务交给线程池管理。这可以帮助我们更好地利用系统资源,并避免频繁地创建和销毁线程所带来的开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值