Java中使用线程时,请不要忘记Spring TaskExecutor组件

时间:2022-04-29
本文章向大家介绍Java中使用线程时,请不要忘记Spring TaskExecutor组件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

当我们实现的web应用程序需要长时间运行一个任务时,Spring TaskExecutor管理组件是一个很好选择,会给我们代码的实现提供很大的方便,也会节省时间和成本,程序的性能相信也有一个提升。

在web应用程序中使用线程是比较常见的实现,特别是需要长时间运行一个任务时,必须使用线程实现。

网络配图

Spring提供了TaskExecutor作为抽象处理执行人。

通过提供Spring TaskExecutor的实现,你将能够注入TaskExecutor类和访问托管线程。

package com.gkatzioura.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AsynchronousService {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private TaskExecutor taskExecutor;
public void executeAsynchronously() {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
//TODO add long running task
}
});
}
}

第一步是Spring应用程序添加TaskExecutor配置

package com.gkatzioura.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.initialize();
return executor;
}
}

我们提供执行人设置,这个过程很简单,我们注入执行人,然后我们提交要执行任务运行的类。

因为我们的异步代码可能需要与其他组件的交互应用程序和注射,一个不错的方法是创建原型作用域可运行实例。

package com.gkatzioura;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class MyThread implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(MyThread.class);
@Override
public void run() {
LOGGER.info("Called from thread");
}
}

最后,注入我们服务的执行者和用它来执行可运行的实例。

package com.gkatzioura.service;
import com.gkatzioura.MyThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AsynchronousService {
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private ApplicationContext applicationContext;
public void executeAsynchronously() {
MyThread myThread = applicationContext.getBean(MyThread.class);
taskExecutor.execute(myThread);
}
}