SpringBoot[第二课] spring环境下利用线程池写一个多线程任务执行器

本文介绍了如何在SpringBoot中利用线程池实现多线程任务执行。通过开启@EnableAsync,定义Task类和ThreadPoolTaskExecutor,创建并发任务。同时,文章讨论了优化方案,使用观察者模式和Spring的事件发布与监听机制,以更优雅地传递状态信息,避免死锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前提

在公司的项目里看到一个多线程包,封装了一些原生多线程的代码,方便萌新使用多线程提高代码执行效率。使用方法就是把一个需要处理大量数据的任务等量拆分为多个子任务,然后像使用集合一样放到一个批次对象里(例如Batch),然后用Batch遍历启动批次中的子任务,并发执行。全部执行完毕之后返回执行结果。对新手来说确实方便,由于项目组中使用spring作为开发框架相当普遍,而spring从3.0以后就引入了对多线程的支持,再配合配置类代替xml文件的特性,可以考虑用spring的线程池,实现与上述一样的功能,实用性有待验证,暂且作为使用spring线程池的小练习。

步骤

要使用spring线程池实现并发,至少需要三块东西:开启并发支持、注册执行器、定义并发任务。

线程池配置类

package com.terry.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncContextConfig {
	 @Bean
     public Executor getExecutor() {
          ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
          executor.setCorePoolSize(5);
          executor.setMaxPoolSize(10);
          executor.setQueueCapacity(25);
          executor.initialize();
          return executor;
	 }
		@Bean
		@Scope("prototype")
		public Task task() {
			return new Task();
		}
}
  • @EnableAsync:开启spring对多线程的支持,可以放在启动类或者配置类上;
  • Task:Task就是定义并发任务的类,必须交给spring容器去初始化才能调起线程池。
  1. ThreadPoolTaskExecutor:getExecutor()方法将ThreadPoolTaskExecutor注册到spring容器中,其中就定义了一个可用的线程池,这是一种注册方法,还有另一种注册执行器的方法,看上去更符合spring的风格: 
    public class AsyncContextConfig implements AsyncConfigurer {
    	@Override
    	public Executor getAsyncExecutor() {
    		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    		taskExecutor.setCorePoolSize(5);
    		taskExecutor.setMaxPoolSize(10);
    		taskExecutor.setQueueCapacity(25);
    		taskExecutor.initialize();
    		return taskExecutor;
    	}
    	@Override
    	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    		AsyncUncaughtExceptionHandler handler = new AsyncUncaughtExceptionHandler() {
    			@Override
    			public void handleUncaughtException(Throwable e, Method m, Object... arg2) {
    				// TODO Auto-generated method stub
    				System.out.println(m.getName() + "抛出异常:" + e.getMessage());
    			}
    		};
    		return handler;
    	}

    定义并发任务 

子任务类:

package com.terry.async;

import org.springframework.scheduling.annotation.Async;
public class Task {
	private Integer index;
	@Async
	public void execute(Batch batch) {
		try {
			Thread.sleep((long)Math.random()*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("任务" + index + "执行成功");
		batch.finish(this.index);
	}
	public Integer getIndex() {
		return index;
	}
	public void setIndex(Integer index) {
		this.index = index;
	}
}

 

  • @Async:@Async修饰的方法被调用时将会在线程池中并发执行;

批次任务容器类:

package com.terry.async;
import java.util.ArrayList;
public class Batch  {
	private ArrayList<Task> taskList;
	private Integer finishedTaskCount;
	private Boolean allowAdd;
	public Batch() {
		super();
		this.taskList = new ArrayList<Task>();
		this.finishedTaskCount = 0;
		this.allowAdd = true;
	}
	public void add(Task t){
		if(this.allowAdd){
			this.taskList.add(t);
		}else{
			System.err.print("执行中。。。");
		}
	}
	public void execute(){
		this.allowAdd=false;
		for(int i=0;i<taskList.size();i++){
			taskList.get(i).execute(this);
		}
		while(this.finishedTaskCount<(this.taskList.size()-1)){
		// 阻塞
		}
		batchFinished();
	}
	protected void batchFinished(){
		System.out.println("批次执行成功");
	}
	public void finish(Integer index) {
		finishedTaskCount++;		
	}
}

测试

package springDemo;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.terry.async.Batch;
import com.terry.async.Task;
import com.terry.config.AsyncContextConfig;
public class TestAsync {
	@Test
	public void test(){
		AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AsyncContextConfig.class);
		Batch batch=new Batch();
		for(int i=0;i<10;i++){
			Task t=new Task();
			t.setIndex(i);
			batch.add(t);
		}
		batch.execute();
		context.close();
	}
}

执行结果:

任务3执行成功
任务2执行成功
任务0执行成功
任务1执行成功
任务4执行成功
任务5执行成功
任务6执行成功
任务7执行成功
任务8执行成功
批次执行成功
任务9执行成功

 优化

上文中Batch在控制主流程终止时用while做了阻塞,这种方式比较原始,容易引起死锁,需要用更优雅的方式在Task和Batch之间传递状态信息,这时候就用到了观察者模式,spring的事件发布与监听机制就是这一模式的经典应用,这种模式有一个突出的优点就是使发布者和监听者之间实现解耦,他们的行为不会直接依赖彼此,而是围绕事件间接产生联系。要形成一套完整的观察者模式,至少需要三块:事件定义、事件发布者定义、事件监听者定义;

事件定义

package com.terry.event;

import org.springframework.context.ApplicationEvent;

public class TaskFinishEvent extends ApplicationEvent {

	private static final long serialVersionUID = -8009414181321590798L;
	private Boolean ifSuccess;

	public TaskFinishEvent(Object source, Boolean ifSuccess) {
		super(source);
		this.setIfSuccess(ifSuccess);
	}
    // getter and setter...
}

spring中定义的事件要继承ApplicationEvent 类,其本身不具有任何功能,构造方法至少要有一个参数,就是上面的Object source,将来传入的是时间的发布者本身,这之后可以定义其他参数(个数、类型不限),作为消息传递时附带的参数(当然不需要也可以不要,其实事件本身就是一个参数)。

事件发布者定义

本文中消息是从子任务传递到批次任务,所以事件的发布者就是子任务类Task,监听者就是Batch。
修改Task.java类如下:

package com.terry.async;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.scheduling.annotation.Async;
import com.terry.event.TaskFinishEvent;

public class Task implements ApplicationEventPublisherAware {
	
	private Integer index;
	private ApplicationEventPublisher publisher;

	@Async
	public void execute() {
		try {
			Thread.sleep((long) Math.random() * 1000);
		} catch (InterruptedException e) {
			this.publisher.publishEvent(new TaskFinishEvent(this, false));
			e.printStackTrace();
		}
		System.out.println("第" + index + "个任务完成");
		this.publisher.publishEvent(new TaskFinishEvent(this, true));
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}

	// getter and setter ...
}

Task实现了ApplicationEventPublisherAware 接口, spring容器会为实现这一接口的类初始化一个ApplicationEventPublisher 属性,这个类就可以用它来发布不同的事件。

事件监听者定义

修改Batch,java如下:

package com.terry.async;

import java.util.ArrayList;
import org.springframework.context.ApplicationListener;
import com.terry.event.TaskFinishEvent;

public class Batch implements ApplicationListener<TaskFinishEvent>  {

	private ArrayList<Task> taskList;
	private Integer finishedTaskCount;

	private Boolean allowAdd;

	public Batch() {
		super();
		this.taskList = new ArrayList<Task>();
		this.finishedTaskCount = 0;
		this.allowAdd = true;
	}

	@Override
	public void onApplicationEvent(TaskFinishEvent e) {
		if (e.getIfSuccess()) {
			finishedTaskCount++;
		}
		if (finishedTaskCount == taskList.size() - 1) {
			batchFinished();
		}
	}

	public void add(Task t) {
		if (this.allowAdd) {
			this.taskList.add(t);
		} else {
			System.err.print("正在执行");
		}
	}

	public void execute() {
		this.allowAdd = false;
		for (int i = 0; i < taskList.size(); i++) {
			taskList.get(i).execute();
		}
	}

	private void batchFinished() {
		System.out.println("批次任务完成!");
	}
}

事件的监听者需要实现ApplicationListener接口,并指定泛型<TaskFinishEvent>,从这种实现方式可知一个监听者只能监听一种事件,实现的方法onApplicationEvent方法接收一个泛型指定的事件参数,作为事件发布之后做出的响应。

 

Spring Boot 提供了对线程管理的支持,包括配置多个线程池。这通常通过`ThreadPoolTaskExecutor`或其更高级的替代品`AsyncConfigurer`来完成。以下是如何设置两个不同的线程池1. 使用 `ThreadPoolTaskExecutor`: ```java import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean(name = "customThreadPool") public ThreadPoolTaskExecutor customThreadPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.initialize(); // 初始化任务执行 return executor; } @Bean(name = "anotherThreadPool") public ThreadPoolTaskExecutor anotherThreadPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(6); // 设置其他属性... return executor; } } ``` 在这里,我们创建了两个线程池,`customThreadPool` 和 `anotherThreadPool`,分别有不同的核心线程数、最大线程数和队列容量。 2. 使用 Spring 的 `@Async` 和 `AsyncConfigurer`: 如果你想要在服务类中异步执行任务,并且想自定义线程池,可以实现`AsyncConfigurer`接口并提供线程池配置: ```java @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 配置线程池属性... return executor; } // 如果需要配置第二个线程池 public Executor getCustomExecutor() { ThreadPoolTaskExecutor customExecutor = ...; // 创建另一个线程池实例 return customExecutor; } } ``` 然后,在需要异步处理的地方,你可以选择使用 `@Async` 注解指定执行哪种线程池
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值