使用弹簧管理的线程创建弹簧线程池

时间:2020-03-31 09:17:24

标签: java spring spring-boot

因此,我试图通过将Java代码迁移到Spring Boot来学习Spring Boot。

我有一部分Java代码,如下所示:

int threadLimit = 5, interval = 2;
ScheduledExecutorService ses = Executors.newScheduledThreadPool(threadLimit);
for (int i = 0; i < executionThreadLimit; i++) {
    WorkerThread worker = new WorkerThread("WorkerThread");
    ses.scheduleAtFixedRate(worker, 0, interval, TimeUnit.SECONDS);
}

此处WorkerThread实现了Runnable;

上述代码的相应Spring Boot替代方法:

自定义池类:

@Configuration
public class Test {

     @Bean
        public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.setPoolSize(5);
            threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
            return threadPoolTaskScheduler;
        }

}

WorkerThread类:

@Component
@Scope("prototype")
public class WorkerThread implements Runnable {

private Logger logger = LogManager.getLogger(this.getClass().getName());

    private String threadName = null;

    @Autowired
    private AppParameter app;

    @Override
    public void run() {
        logger.info("Thread :: " + this + " is running -- > " + app.getA() + " && " + app.getB());
    }
}

测试类:

@Component
public class TestCommandLineRunner implements CommandLineRunner {

private final Logger logger = LogManager.getLogger(this.getClass().getName());

@Autowired
private ThreadPoolTaskScheduler taskScheduler;

@Override
public void run(String... args) throws Exception {

    int threadLimit = 5, interval = 2000;  // these 2 are dynamic values but provided statically for testing purposes
    for(int i = 0; i< threadLimit; i++) {
        WorkerThread wt = new WorkerThread();
        taskScheduler.scheduleAtFixedRate(wt, interval);
    }
}

}

现在这是我的问题所在。如果我需要启动5个WorkerThread实例,则必须做WorkerThread wt = new WorkerThread();,但是如果这样做,则WorkerThread将不再是Spring托管的bean。

所以我的问题是如何创建线程类为Spring Managed Bean的线程池?

我只是开始使用Spring Boot,因此有人会介意帮助我吗?谢谢。

我已经参考了以下文档, https://www.baeldung.com/spring-task-scheduler https://mkyong.com/spring/spring-and-java-thread-example/ 但无法提出可行的解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用ObjectFactory

实例化它们
@Autowired
private ThreadPoolTaskScheduler taskScheduler;

@Autowired
private ObjectFactory<WorkerThread> threadFactory;

@Override
public void run(String... args) throws Exception {

    int threadLimit = 5, interval = 2000;  // these 2 are dynamic values but provided statically for testing purposes
    for(int i = 0; i< threadLimit; i++) {
        WorkerThread wt = threadFactory.getObject();
        taskScheduler.scheduleAtFixedRate(wt, interval);
    }
}