当然方法不止一种 如注解:@PostConstruct 或者springBoot项目实现 ApplicationRunner
importcom.gpyh.gms.server.service.goods.GoodsInfoSynchService;importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.context.ApplicationListener; importorg.springframework.context.annotation.DependsOn; importorg.springframework.context.event.ContextRefreshedEvent; importorg.springframework.stereotype.Component; importjava.util.concurrent.ExecutorService; importjava.util.concurrent.Executors; //@DependsOn({"需要依赖的类(启动的线程,需要在这个类后面完成初始化可添加)"})publicclassMyApplicationListenerimplementsApplicationListener<ContextRefreshedEvent> { privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyApplicationListener.class); privateGoodsInfoSynchServicegoodsInfoSynchService; publicvoidonApplicationEvent(ContextRefreshedEventevent) { // 创建单线程池ExecutorServiceexecutor=Executors.newSingleThreadExecutor(); logger.info("线程启动监控"); executor.execute(()->**需要执行的任务**); } }
importorg.springframework.stereotype.Component; importjavax.annotation.PostConstruct; publicclassQueueMonitor { publicvoidstartQueueMonitor() { Threadthread=newThread(newYourQueueMonitorRunnable()); thread.start(); } privateclassYourQueueMonitorRunnableimplementsRunnable { publicvoidrun() { // 监控队列的逻辑 } } }