SpringBoot :如何运行一个永久运行的线程

实际开发中,经常会有永久运行一个线程的需求,如: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();
        }
    }
}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了多种方式来运行线程。以下是一些常见的编程思路: 1. 实现Runnable接口 创建一个类,实现Runnable接口并重写run()方法。使用Thread类的构造函数将该Runnable对象传递给Thread对象,然后调用start()方法启动线程。 ```java @Component public class MyRunnable implements Runnable { @Override public void run() { // 线程执行的代码 } } // 在需要启动线程的地方调用 MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); ``` 2. 继承Thread类 创建一个类,继承Thread类并重写run()方法。实例化该类并调用start()方法启动线程。 ```java @Component public class MyThread extends Thread { @Override public void run() { // 线程执行的代码 } } // 在需要启动线程的地方调用 MyThread myThread = new MyThread(); myThread.start(); ``` 3. 使用线程池 创建一个线程池,将任务提交给线程池执行。Spring Boot提供了ThreadPoolTaskExecutor类来简化线程池的创建和管理。 ```java @Component public class MyService { @Autowired private ThreadPoolTaskExecutor taskExecutor; public void doTask() { taskExecutor.execute(() -> { // 线程执行的代码 }); } } ``` 4. 使用@Async注解 在Spring Boot中,可以使用@Async注解将方法标记为异步执行。Spring Boot会自动创建一个线程池来执行带有@Async注解的方法。 ```java @Component public class MyService { @Async public void doTask() { // 线程执行的代码 } } ``` 需要在启动类上添加@EnableAsync注解开启异步执行功能。 ```java @SpringBootApplication @EnableAsync public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值