简体   繁体   English

如何在Spring bean中启动线程

[英]how to start a thread in Spring bean

I want to run a thread in spring application 我想在Spring应用程序中运行线程

    @Component
    public class MyServiceCreationListener {


        public void startThread() {

            Thread t = new Thread(new MyThread());
            t.start();

        }
    }

Here i used Thread t = new Thread(new MyThread()); 在这里我使用了Thread t = new Thread(new MyThread()); This is wrong way. 这是错误的方式。

Please provide solution for this to spring manage MyThread like a spring bean so we can autowire it into other beans and by calling start() method we can access it 请为此提供解决方案以像Spring bean一样对MyThread进行弹簧管理,以便我们可以将其自动连接到其他bean中,并通过调用start()方法来访问它

Here is Thread class 这是线程类

@Component
public class MyThread implements Runnable {

    public void run() {

        System.out.println("Inside run()");

    }

}

By default, spring beans are singleton, but Thread's run method will only run once. 默认情况下,spring bean是单例的,但是Thread的run方法将只运行一次。 After that it is considered in a state different to RUNNABLE. 之后,它被认为处于不同于RUNNABLE的状态。

LifeCycle of Thread in Java Java线程的生命周期

So, you need to create a new object every time and you can do that using prototype scope and ObjectFactory . 因此,您每次都需要创建一个新对象,并且可以使用prototype范围和ObjectFactory进行创建

Extending Thread : 扩展Thread

@Bean
@Scope("prototype")
public class MyThread implements Runnable {

    public void run() {

        System.out.println("Inside run()");

    }
}

And then: 接着:

@Component
public class MyServiceCreationListener {

    @Autowired
    ObjectFactory<MyThread> myThreadFactory;

    public void startThread() {
        myThreadFactory.getObject().start();
    }
}

This code has not been tested, it just for you to get an idea. 这段代码尚未经过测试,仅供您参考。

You can find some examples here: Spring and java threads 您可以在此处找到一些示例: Spring和Java线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM