多线程在Spring中的使用

2023-12-25 18:49:25 浏览数 (1)

案例1:自定义多播器和多线程有什么关系?

自定义多播器

自定义多播器如下所示,其实和我们自定义其他的不太一样,因为其他的自定义不会有value值,为什么此处必须要有value = "applicationEventMulticaster"???

代码语言:javascript复制
@Component(value = "applicationEventMulticaster")
public class Myulticaster extends SimpleApplicationEventMulticaster{
    public MyMulticaster () {
        setTaskExecutor(Executors.newSingleThreadExecutor());
    }
}

答案在源码中

AbstractApplicationContext的initApplicationEventMulticaster()方法用于初始化Multicaster,Spring已经把多播器的名字写在源码中

代码语言:javascript复制
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";


protected void initApplicationEventMulticaster() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //如果beanFactory中有applicationEventMulticaster的bean,就把该Bean赋值给this.applicationEventMulticaster
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			}
		}
		else {
            //否则就创建一个SimpleApplicationEventMulticaster
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		}
	}

案例

下面是自定义的listener

代码语言:javascript复制
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {

    System.out.println("-----------MyApplicationListener-------------");
    
    try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace(); } finally { }
        System.out.println("-----------MyApplicationListener over-------------");
    }
}

当不不自定义多播器的时候,上面listener是同步执行的,如果定义了多波器,是异步执行的。

源码

https://github.com/cbeann/Demooo/blob/master/spring-demo/src/main/java/ioc/AppMyulticasterDemo.java

案例2:异步@Async

代码语言:javascript复制
@Service
public class EmailService {

  @Async
  public void sendEmail() {
    System.out.println("---start--");
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
    }

    System.out.println("---end--");
  }
}

调用EmailService.sendEmail()的时候是异步,也是用了线程池

源码

https://github.com/cbeann/Demooo/blob/master/springboot-demo/src/main/java/com/example/theadpool/App.java

参考

SpringIOC源码解析之--如何实现多播器的异步多播的(ApplicationEventMulticaster)_pengweismile的专栏-CSDN博客

0 人点赞