Java 在 springboot 应用程序中启动线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37390718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:16:13  来源:igfitidea点击:

Start thread at springboot application

javaspringspring-boot

提问by

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

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

@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)
     }
}

采纳答案by M. Deinum

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

不要自己乱搞线程。Spring(以及普通的 Java)对此有一个很好的抽象。

First create a bean of the type TaskExecutorin your configuration

首先TaskExecutor在您的配置中创建一个该类型的bean

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

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

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

@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 管理的类。

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 CommandLineRunnerhere because that will execute after all beans have bean initialized.

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