自定义线程管理器开启异步任务
文章目录
**第一步:编写一个类获得bean的类**
//可以让不在容器中的类获得容器中的类
@Component
public class SpringContainerUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext1) throws BeansException {
applicationContext=applicationContext1;
}
public static <T> T getBean(Class<T> tClass){
return applicationContext.getBean(tClass);
}
}
第二步:编写异步任务管理器
//只需要全局操控一个线程池,所以需要使用单例模式
public class AsyncManager {
private ThreadPoolTaskExecutor poolTaskExecutor;
private static AsyncManager asyncManager;
// 私有化构造方法
private AsyncManager(){
poolTaskExecutor=SpringContainerUtils.getBean(ThreadPoolTaskExecutor.class);
}
//获得实例,如果存在直接返回,不存在就实例化
public static AsyncManager getInstance(){
if (asyncManager==null){
asyncManager=new AsyncManager();
}
return asyncManager;
}
// 调用线程池做异步任务
public void executeByAsync(Runnable runnable){
poolTaskExecutor.execute(runnable);
}
}
第三步:编写Runnable工厂
public class RunnableFactory {
public static Runnable getRunnable(){
BrandMapper bean = SpringContainerUtils.getBean(xxx.class);
Runnable runnable = ()->{
//需要做异步操作的代码
xxx.doSomethin();
};
return runnable;
}
}
第四步:调用方法开启异步任务
public void doSomethin(){
//在需要使用异步操作的地方调用方法即可
AsyncManager.getInstance().executeByAsync(RunnableFactory.getRunnable());
}