Spring通过@Async注解实现多线程

1.在WEB-INF下创建线程池配置文件config.properties

corePoolSize=10
maxPoolSize=200
keepAliveSeconds=1
queueCapacity=24

2.创建线程池配置类AsyncTaskConfig

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncTaskConfig {

	// ThredPoolTaskExcutor的处理流程
	// 当池子大小小于corePoolSize,就新建线程,并处理请求
	// 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
	// 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
	// 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁
	@Bean
	public Executor myTaskAsyncPool() throws Exception {
		String pro = this.getClass().getResource("/").getPath().split("WEB-INF")[0]+ "WEB-INF/config.properties";
		FileInputStream fs = new FileInputStream(pro);
		Properties p = new Properties();
		p.load(new InputStreamReader(fs, "utf-8"));
		Integer corePoolSize = Integer.parseInt(p.getProperty("corePoolSize"));
		Integer maxPoolSize = Integer.parseInt(p.getProperty("maxPoolSize"));
		Integer keepAliveSeconds = Integer.parseInt(p.getProperty("keepAliveSeconds"));
		Integer queueCapacity = Integer.parseInt(p.getProperty("queueCapacity"));
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
        executor.setCorePoolSize(corePoolSize);  
        executor.setMaxPoolSize(maxPoolSize);    
        executor.setKeepAliveSeconds(keepAliveSeconds);  
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("MyExecutor-");   
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务  
        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行  
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());  
        executor.initialize(); 
		return executor;
	}
}

3.创建taskService并添加方法

@Async("myTaskAsyncPool")
public void transJkrz(Map<String, Object> m) {
    System.out.println("我被异步调用了");
}

4.在Controller中调用方法

@RequestMapping(value = "list.htm", method = {RequestMethod.GET, RequestMethod.POST })
public void list(HttpServletRequest request) throws Exception{
  List<Map> list = new ArrayList<Map>();//可根据业务查询库中数据
  for(Map m : list){
      taskService.transJkrz(m);
  }
}


猜你喜欢

转载自blog.csdn.net/rexueqingchun/article/details/81004870