实际开发中,经常会有永久运行一个线程的需求,如:socket服务端、UDP接收、监视数据等,下面列出两种实现方法:
一、写一个继承Thread的类,重写run方法,并在main函数里面启动
继承Thread的类的代码
public class MyThread extends Thread{
public MyThread(){
}
@Override
public void run() {
try{
while (true) {
// 这里写业务逻辑
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
main 函数
public static void main(String[] args) {
applicationContext = SpringApplication.run(BusinessApplication.class, args);
//增加以下两句代码
MyThread myThread=new MyThread();
myThread.start();
}
这种方式的缺点是会污染main函数。
二、直接写一个实现Runnable的类
需要增加@Component注解,并在init方法里启动线程,代码如下:
@Component
public class UdpAcceptThread implements Runnable{
//可以直接使用 @Autowired,这里只是举个例子,根据实际需要删除代码
@Autowired
IMyService myService;
@PostConstruct
public void init(){
//启动线程实例
new Thread(this).start();
}
@Override
public void run() {
try {
//noinspection InfiniteLoopStatement
while (true) {
//这里写业务逻辑
}
catch (Exception ex){
ex.printStackTrace();
}
}
}