前提
在公司的项目里看到一个多线程包,封装了一些原生多线程的代码,方便萌新使用多线程提高代码执行效率。使用方法就是把一个需要处理大量数据的任务等量拆分为多个子任务,然后像使用集合一样放到一个批次对象里(例如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容器去初始化才能调起线程池。
- 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方法接收一个泛型指定的事件参数,作为事件发布之后做出的响应。