在springboot应用程序中启动线程 [英] Start thread at springboot application

查看:2387
本文介绍了在springboot应用程序中启动线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Spring Boot启动后执行一个Java类(其中包含我要执行的Java线程).我的初始代码:

I want to execute a java class (which contains a java thread I want to execute) after spring boot starts. My initial code:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

这是我想在开始时执行的代码:

And here is is the code I want to execute at start:

public class SimularProfesor implements Runnable{

    // Class atributes

    // Constructor
    public SimularProfesor() {
        //Initialization of atributes
    }

    @Override
    public void run() {
        while(true) {
            // Do something
        }
    }
}

我怎么称呼这个线程?这是我应该做的:

How can I call this thread? This is what I'm supposed to do:

@SpringBootApplication
public class Application {
     public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        // Call thread (constructor must be executed too)
     }
}

推荐答案

不要自己弄乱线程. Spring(还有普通的Java)对此有一个很好的抽象.

Don't mess around with threads yourself. Spring (and also plain Java) has a nice abstraction for that.

首先在您的配置中创建类型为TaskExecutor的Bean

First create a bean of the type TaskExecutor in your configuration

@Bean
public TaskExecutor taskExecutor() {
    return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}

然后创建一个CommandLineRunner(尽管ApplicationListener<ContextRefreshedEvent>也可以)来安排您的任务.

Then create a CommandLineRunner (although an ApplicationListener<ContextRefreshedEvent> would also work) to schedule your task.

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
    return new CommandLineRunner() {
        public void run(String... args) throws Exception {
            executor.execute(new SimularProfesor());
        }
    }
}

您当然也可以在春季之前安排自己的课堂.

You could of course make also your own class managed by spring.

这样做的好处是Spring还将为您清理线程,而您不必自己考虑.我在这里使用了CommandLineRunner,因为它将在所有bean都初始化之后执行.

Advantage of this is that Spring will also cleanup the threads for you and you don't have to think about it yourself. I used a CommandLineRunner here because that will execute after all beans have bean initialized.

这篇关于在springboot应用程序中启动线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆