温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springmvc如何配置线程池Executor做多线程并发操作

发布时间:2021-08-20 13:46:31 来源:亿速云 阅读:360 作者:小新 栏目:编程语言

这篇文章主要介绍springmvc如何配置线程池Executor做多线程并发操作,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

加载xml文件

在ApplicationContext.xml文件里面添加

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

xmlns文件并且xsi:schemaLocation中添加

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd

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

以上是“springmvc如何配置线程池Executor做多线程并发操作”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI