springmvc配置线程池Executor做多线程并发操作的代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springmvc配置线程池Executor做多线程并发操作的代码实例

  2021-04-03 我要评论

加载xml文件

在ApplicationContext.xml文件里面添加

xmlns:task="http://www.springframework.org/schema/task" 

xmlns文件并且xsi:schemaLocation中添加

在spring中配置Executor

在ApplicationContext.xml文件里面添加

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> 
    <!-- 核心线程数 -->    
    <property name="corePoolSize" value="${task.core_pool_size}" /> 
    <!-- 最大线程数 -->  
    <property name="maxPoolSize" value="${task.max_pool_size}" /> 
    <!-- 队列最大长度 --> 
    <property name="queueCapacity" value="${task.queue_capacity}" /> 
    <!-- 线程池维护线程所允许的空闲时间,默认为60s --> 
    <property name="keepAliveSeconds" value="${task.keep_alive_seconds}" /> 
  </bean> 
  <!-- 注解式 --> 
  <task:annotation-driven /> 

在dbconfig.properties添加

maxOpenPreparedStatements=20 
removeAbandoned=true 
removeAbandonedTimeout=1800 
logAbandoned=true 

这是分别对线程池做配置

添加依赖注入

在所需要的service或者controller类里面添加

@Resource(name = "taskExecutor") 
private TaskExecutor taskExecutor; 

使用线程池进行并发操作

代码如下

taskExecutor.execute(new Runnable() { 
  @Override 
  public void run() { 
    // TODO Auto-generated method stub 
    try { 
       //要进行的并发操作 
    } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
  } 
}); 

提示

注意在线程中操作变量时候变量的作用域范围。需要在这个controller或者sevice中声明变量如下

@Controller 
public class IndexController { 
int studentscount = 0; 
@RequestMapping(value = "/index.html") 
  public ModelAndView goIndex() { 
    logBefore(logger, "列表Center"); 
    ModelAndView mv = this.getModelAndView(); 
        taskExecutor.execute(new Runnable() { 
        @Override 
        public void run() { 
          // TODO Auto-generated method stub 
          // 得到所有学生人数 
          try { 
                     studentscount = coursesService.getStudentCount(pd); 
          } catch (Exception e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
          } 
        } 
      }); 
         mv.addObject("studentscount", studentscount); 
         mv.setViewName("common/index"); 
         return mv; 
} 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们