一直不太明白,线程池在实际应用当中到底扮演什么样的角色,有什么场景要用到,只有真正的项目设计的时候才能逐渐理解,实践出真知说的就是这么个道理。
使用多线程,往往是创建Thread,或者是实现runnable接口,用到线程池的时候还需要创建Executors,spring中有十分优秀的支持,就是注解@EnableAsync就可以使用多线程,@Async加在线程任务的方法上(需要异步执行的任务),定义一个线程任务,通过spring提供的ThreadPoolTaskExecutor就可以使用线程池
首先定义配置类
这个配置类需要实现AsyncConfiguer接口,并实现它的方法
- 异步线程的执行者,在里面配置自动执行的东西,比如线程池参数
- 线程异常处理
package ds.watsons.app.label.config;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configurable
@EnableAsync
public class TreadPoolConfigTest implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
// TODO Auto-generated method stub
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池数量,方法: 返回可用处理器的Java虚拟机的数量。
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
//最大线程数量
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*5);
//线程池的队列容量
executor.setQueueCapacity(Runtime.getRuntime().availableProcessors()*2);
//线程名称的前缀
executor.setThreadNamePrefix("this-excutor-");
// setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
// CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
//executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/*异步任务中异常处理*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return new SimpleAsyncUncaughtExceptionHandler();
}
}
- 线程任务类
package ds.watsons.app.label.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class TreadTasks {
@Async
public void startMyTreadTask() {
System.out.println("this is my async task");
}
}
- 调用异步线程任务
package ds.watsons.app.label.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import ds.watsons.app.label.service.TreadTasks;
@Controller
public class AsyncTaskUse {
@Autowired
private TreadTasks treadTasks;
@GetMapping("/startMysync")
public void useMySyncTask() {
treadTasks.startMyTreadTask();
}
}
请求url
/startMysync
返回结果:
this is my async task
网友评论