- 自定义线程池
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setAllowCoreThreadTimeOut(true);
taskExecutor.setCorePoolSize(2);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
taskExecutor.setThreadFactory(new CustomizableThreadFactory("test--springThread-pool-"));
return taskExecutor;
}
自定义spring只默认执行ApplicationEvent的执行器
@Bean
public SimpleApplicationEventMulticaster applicationEventMulticaster(ConfigurableListableBeanFactory beanFactory,
ThreadPoolTaskExecutor taskExecutor) {
SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(beanFactory);
multicaster.setTaskExecutor(taskExecutor);
return multicaster;
}
2.原理:
spring启动中,AbstractApplicationContext#refresh()中,initApplicationEventMulticaster()会初始化一个ApplicationEventMulticaster实例,如果beanFactory容器中能containLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME )
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
就是自定义了ApplicationEventMulticaster,那就用这个 ;如果没有,就spring自己new一个ApplicationEventMulticaster实例this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);,并把单例放到容器中。
3.执行代码的地方
applicationContext.publishEvent(event)-->abstractApplicationContext.publisEvent(event)--->getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);---->Executor executor = getTaskExecutor();,这个就是自定义的线程池
网友评论