场景:定时任务调度,实时监控
实现:基于两个类实现,如下:
package com.demo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
/**
* 配置类
*/
@Component
public class TestC implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
TestR runT = new TestR();
runT.run();
}
}
package com.demo;
/**
* 运行类
*/
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestR {
public void run() {
Thread newThread = new Thread() {
@Override
public void run() {
while (true) {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("hello world~~~~~~~~~~~~~~~~~~~~~");
System.out.println("hello world");
}
}
};
newThread.start();
}
}
控制台打印如下
2023-05-26 13:29:44 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:49 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:54 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:59 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
总结:Spring容器中注入一个组件TestC且组件自定义初始化逻辑,初始化逻辑中调用另一个类TestR的方法,该方法中创建一个线程并运行。