1、实现Callable接口
//定义类StudentThread实现Callable接口,其中DealStudentInfoRes为业务处理完返回的结果集DTO,DealStudentInfoResq为需要处理的学生信息的DTO
//DealStudentInfoResq学生信息DTO
@Data
@ApiModel("学生信息")
@Builder
public class DealStudentInfoResq {
@ApiModelProperty("学生编码")
private String studentCode;
@ApiModelProperty("学生姓名")
private String studentName;
}
//DealStudentInfoRes学生信息处理完成后返回的DTO
@Data
@Builder
@ApiModel("学生信息处理结果")
public class DealStudentInfoRes {
@ApiModelProperty("编号")
private String IDCard;
@ApiModelProperty("处理成功失败标识")
private String flag;
@ApiModelProperty("处理结果")
private String ResultInfo;
}
//类StudentThread
public class StudentThread implements Callable<DealStudentInfoRes> {
//控制要处理学生信息的数量
private CountDownLatch countDownLatch;
//需要处理的学生信息
private DealStudentInfoResq dealStudentInfoResq;
public StudentThread(CountDownLatch countDownLatch, DealStudentInfoResq dealStudentInfoResq) {
this.countDownLatch = countDownLatch;
this.dealStudentInfoResq = dealStudentInfoResq;
}
@Override
public DealStudentInfoRes call() throws Exception {
//处理学生信息业务逻辑 具体业务逻辑自己实现,这里只模拟处理后的结果
DealStudentInfoRes dealStudentInfoRes = null;
dealStudentInfoRes.setFlag("1");
dealStudentInfoRes.setIDCard("123");
dealStudentInfoRes.setResultInfo("成功");
//数量减一 至关重要 用来控制需要处理学生信息的数量没处理完一次都要减一
countDownLatch.countDown();
return dealStudentInfoRes;
}
}
//定义接口
public interface StudentInfoDeal {
public void dealStudentInfo();
}
//调用多线程实现接口
@Service
@Slf4j
public class StudentInfoDealImpl implements StudentInfoDeal {
//设置默认的线程数量
@Value("${studentThread.count}")
private int threadCount;
public int getThreadCount() {
return threadCount;
}
public void setThreadCount(int threadCount) {
this.threadCount = threadCount;
}
@Override
public void dealStudentInfo() {
List<DealStudentInfoResq> dealStudentInfoResqs = new ArrayList<>();
//构造学生信息数据 根据自己情况处理待处理的数据信息
for (int i = 0; i < 10; i++) {
DealStudentInfoResq dealStudentInfoResq = DealStudentInfoResq.builder()
.studentCode("1243" + i)
.studentName("test" + i).build();
dealStudentInfoResqs.add(dealStudentInfoResq);
}
//设置需要处理的学生数量
CountDownLatch countDownLatch = new CountDownLatch(dealStudentInfoResqs.size());
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List<DealStudentInfoRes> dealStudentInfoRes = new ArrayList<>();
for (Iterator<DealStudentInfoResq> it = dealStudentInfoResqs.iterator(); it.hasNext(); ) {
DealStudentInfoResq studentInfoResq = it.next();
Callable<DealStudentInfoRes> studentInfoResqCallable = new StudentThread(countDownLatch, studentInfoResq);
//调用多线程
Future<DealStudentInfoRes> future = executorService.submit(studentInfoResqCallable);
try {
//获得每次处理的结果
dealStudentInfoRes.add(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
try {
//注意必不可少 ,以方便后面批量处理业务数据,这里主要是保证处理完所有的学生信息
countDownLatch.await();
//根据dealStudentInfoRes处理后续的业务逻辑 此处省略
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}