springboot+Thread启动后台线程并支持注解

本文介绍了一个使用Java实现的后台线程实例,通过Spring框架的@Component注解定义了一个名为DataProcessController的类,该类实现了Runnable接口,用于执行数据处理任务。在类中,通过@PostConstruct注解的方法init()启动了一个新的线程,线程内部采用无限循环的方式持续检查linkedBlockingQueue队列是否有任务待处理,如果没有任务则线程休眠100毫秒,如果有任务则调用executeTask()方法进行处理。

后台线程启动实例

@Component
public class DataProcessController implements Runnable{

	@Value("${params}")
	private String params;

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@PostConstruct
	public void init(){
		//启动线程实例
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		synchronized(this){
			while (true){
				try {
					if(linkedBlockingQueue.isEmpty()){
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}else{
						executeTask();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void executeTask(){
		//具体业务
	}
}
### Spring Boot中配置线程池实现多线程处理 #### 使用`@Configuration`类定义线程池 Bean 为了在Spring Boot应用程序中配置自定义线程池,可以通过创建一个新的配置类使用`@Bean`注解来声明一个`ThreadPoolTaskExecutor`类型的bean。这允许开发者指定诸如核心线程数、最大线程数等参数。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean(name = "taskExecutor") public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数为CPU核数的两倍 int coreSize = Runtime.getRuntime().availableProcessors() * 2; // 设置最大线程数为CPU核数的四倍 int maxSize = Runtime.getRuntime().availableProcessors() * 4; executor.setCorePoolSize(coreSize); executor.setMaxPoolSize(maxSize); executor.setQueueCapacity(100); // 队列容量设为100 executor.setThreadNamePrefix("MyTask-"); // 线程名称前缀 // 初始化时启动最小数量的核心线程 executor.initialize(); return executor; } } ``` 上述代码片段展示了如何通过编程方式配置线程池[^3]。 #### 创建异步方法执行任务 为了让某个服务的方法能够被多个线程发调用,可以在该方法上加上`@Async`注解确保已经启用了异步支持(即,在任意配置文件里添加`@EnableAsync`)。下面的例子说明了这一点: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { private final ThreadPoolTaskExecutor taskExecutor; @Autowired public AsyncTaskService(ThreadPoolTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } @Async("taskExecutor") // 指定使用的线程池名 public void executeAsyncTask(int i){ System.out.println( Thread.currentThread().getName()+" is executing : "+i+" at time:"+System.currentTimeMillis()); } } ``` 这段程序实现了简单的后台任务调度功能,其中每个请求都会由不同的工作线程独立完成[^1]。 #### 测试异步任务的效果 最后一步是在控制器或者其他组件内测试这个新特性的工作情况。这里给出了一种可能的方式来进行验证: ```java @RestController @RequestMapping("/tasks") public class AsyncController { @Autowired private AsyncTaskService asyncTaskService; @GetMapping("/async/{count}") public String invokeTasks(@PathVariable Integer count) throws InterruptedException{ long start=System.currentTimeMillis(); for (int i = 0 ; i<count;i++){ asyncTaskService.executeAsyncTask(i); } while(System.currentTimeMillis()-start<5000){} //等待一段时间让所有任务结束 return "All tasks have been submitted!"; } } ``` 此段代码提供了一个HTTP端点用于触发一系列异步操作,且会暂停主线程直到预计所有的子任务都已完成才返回响应给客户端[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值