溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springmvc如何配置線程池Executor做多線程并發(fā)操作

發(fā)布時間:2021-08-20 13:46:31 來源:億速云 閱讀:380 作者:小新 欄目:編程語言

這篇文章主要介紹springmvc如何配置線程池Executor做多線程并發(fā)操作,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

加載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"> 
    <!-- 核心線程數(shù) -->    
    <property name="corePoolSize" value="${task.core_pool_size}" /> 
    <!-- 最大線程數(shù) -->  
    <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;

使用線程池進行并發(fā)操作

代碼如下

taskExecutor.execute(new Runnable() { 
  @Override 
  public void run() { 
    // TODO Auto-generated method stub 
    try { 
       //要進行的并發(fā)操作 
    } 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 
          // 得到所有學生人數(shù) 
          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做多線程并發(fā)操作”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI