ThreadPoolTaskExecutor异步线程池

原文地址:http://blog.csdn.net/luwei42768/article/details/54927246

一、在spring配置文件中配置

<!-- 异步线程池 -->  
    <bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
      <!-- 核心线程数  -->  
      <property name="corePoolSize" value="3" />  
      <!-- 最大线程数 -->  
      <property name="maxPoolSize" value="20" />  
      <!-- 队列最大长度 >=mainExecutor.maxSize -->  
      <property name="queueCapacity" value="1000" />  
      <!-- 线程池维护线程所允许的空闲时间 -->  
      <property name="keepAliveSeconds" value="300" />  
      <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->  
      <property name="rejectedExecutionHandler">  
        <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />  
      </property>  
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

二、在service类中注入 
@Autowired 
private ThreadPoolTaskExecutor threadPool;

三、service方法中使用

public void doSomething(){
    threadPool.execute(new Runnable() {

            @Override
            public void run() {
                //异步执行耗时的业务任务
            }
        });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

完成

备注:如果要想得到耗时任务的返回结果可以如下使用:

String resp="";
Future<String> task = threadPool.submit(new Callable<String>(){

            @Override
            public String call() throws Exception {
                String callbackResp = HttpUtils.post(Url, params, "utf-8");
                return callbackResp;
            }
        });
        try {   
        //注意task.get()会阻塞,直到返回数据为止,所以一般这样用法很少用
        resp=task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/luoxiang183/article/details/74010885